fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <string.h>
  5.  
  6. #define BUFFER_SIZE 25
  7. #define READ 0
  8. #define WRITE 1
  9.  
  10. int main(void)
  11. {
  12. pid_t pid;
  13. //open two pipes, one for each direction
  14. int mypipefd[2];
  15. int mypipefd2[2];
  16.  
  17. /* create the pipe */
  18. if (pipe(mypipefd) == -1 || pipe(mypipefd2) == -1) {
  19. fprintf(stderr,"Pipe failed");
  20. return 1;
  21. }
  22.  
  23. /* now fork a child process */
  24. pid = fork();
  25.  
  26. if (pid < 0) {
  27. fprintf(stderr, "Fork failed");
  28. return 1;
  29. }
  30.  
  31. if (pid > 0) { /* parent process */
  32. int writeValue=10;
  33. int readValue=0;
  34. close(mypipefd[READ]); //close read end, write and then close write end
  35. write(mypipefd[WRITE],&writeValue,sizeof(writeValue)); //write to pipe one
  36. printf("Parent: writes value : %d\n", writeValue);
  37. close(mypipefd[WRITE]);
  38. close(mypipefd2[WRITE]); //close write end, read, and then close read end
  39. read(mypipefd2[READ],&readValue,sizeof(readValue));
  40. printf("Parent: reads value : %d\n", readValue);
  41. close(mypipefd2[READ]);
  42. }
  43. else { /* child process */
  44. int writeValue=20;
  45. int readValue=0;
  46. close(mypipefd[WRITE]); //close write end, read, and then close read end
  47. read(mypipefd[READ],&readValue,sizeof(readValue));
  48. printf("child: read value : %d\n", readValue);
  49. writeValue+=readValue;
  50. close(mypipefd[READ]);
  51. close(mypipefd2[READ]); //close read end, write and then close write end
  52. write(mypipefd2[WRITE],&writeValue,sizeof(writeValue));
  53. printf("child: writeValue value : %d\n", writeValue);
  54. close(mypipefd2[WRITE]);
  55.  
  56. }
  57.  
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
child: read value : 10
child: writeValue value : 30
Parent: writes value : 10
Parent: reads value : 30