fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6.  
  7. // we'll be setting up an array of four descriptors
  8. #define PARENT_READ 0
  9. #define CHILD_WRITE 1
  10. #define CHILD_READ 2
  11. #define PARENT_WRITE 3
  12.  
  13. int main()
  14. {
  15. int fd[4];
  16. char msg[256];
  17. pid_t pid;
  18.  
  19. pipe(fd); // [0] = parent-read, [1] = child-write
  20. pipe(fd+2); // [0] = child-read, [1] = parent-write
  21.  
  22. if((pid = fork()) == 0)
  23. {
  24. // child process.
  25. close(fd[PARENT_READ]);
  26. close(fd[PARENT_WRITE]);
  27.  
  28. read(fd[CHILD_READ], msg, sizeof(msg));
  29. printf("READ = %s", msg);
  30. strcpy(msg, "YES");
  31. write(fd[CHILD_WRITE], msg, strlen(msg)+1);
  32.  
  33. close(fd[CHILD_READ]);
  34. close(fd[CHILD_WRITE]);
  35.  
  36. return EXIT_SUCCESS;
  37. }
  38.  
  39. // parent process
  40. close(fd[CHILD_READ]);
  41. close(fd[CHILD_WRITE]);
  42.  
  43. strcpy(msg, "HI!! YOU THERE");
  44. write(fd[PARENT_WRITE], msg, strlen(msg)+1);
  45. read(fd[PARENT_READ], msg, sizeof(msg));
  46. printf("\nACK RECEIVED %s\n", msg);
  47.  
  48. close(fd[PARENT_READ]);
  49. close(fd[PARENT_WRITE]);
  50.  
  51. return EXIT_SUCCESS;
  52. }
Success #stdin #stdout 0s 2248KB
stdin
Standard input is empty
stdout
READ = HI!! YOU THERE
ACK RECEIVED YES