fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<unistd.h>
  4. #include<sys/wait.h>
  5.  
  6. #define BUFFER_SIZE 256
  7.  
  8. int main() {
  9. int pipefd[2];
  10. pid_t pid;
  11. char buffer[BUFFER_SIZE];
  12. int nbytes;
  13.  
  14. // Create pipe
  15. if (pipe(pipefd) == -1) {
  16. perror("pipe");
  17. exit(EXIT_FAILURE);
  18. }
  19.  
  20. // Fork a child process
  21. pid = fork();
  22.  
  23. if (pid == -1) {
  24. perror("fork");
  25. exit(EXIT_FAILURE);
  26. }
  27.  
  28. if (pid == 0) { // Child process
  29. // Close the write end of the pipe
  30. close(pipefd[1]);
  31.  
  32. // Read from the pipe
  33. nbytes = read(pipefd[0], buffer, BUFFER_SIZE);
  34. if (nbytes == -1) {
  35. perror("read");
  36. exit(EXIT_FAILURE);
  37. }
  38.  
  39. printf("Child received message: %s", buffer);
  40.  
  41. // Close the read end of the pipe
  42. close(pipefd[0]);
  43. exit(EXIT_SUCCESS);
  44. } else { // Parent process
  45. // Close the read end of the pipe
  46. close(pipefd[0]);
  47.  
  48. // Write to the pipe
  49. printf("Enter message to send to child: ");
  50. fgets(buffer, BUFFER_SIZE, stdin);
  51. write(pipefd[1], buffer, BUFFER_SIZE);
  52.  
  53. // Close the write end of the pipe
  54. close(pipefd[1]);
  55.  
  56. // Wait for the child to finish
  57. wait(NULL);
  58. exit(EXIT_SUCCESS);
  59. }
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Child received message: Enter message to send to child: