fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include<string.h>
  6.  
  7. int main(){
  8.  
  9. int pipefd1[2]; //msg from parent to child
  10. int pipefd2[2]; //msg from child to child1
  11.  
  12. char write_msg1[100];
  13. char write_msg2[100];
  14. char read_msg1[100];
  15. char read_msg2[100];
  16.  
  17.  
  18. if(pipe(pipefd1)==-1){printf("error"); return 1;}
  19. if(pipe(pipefd2)==-1){printf("error"); return 1;}
  20.  
  21. printf("Enter the msg sent from parent to child:");
  22. scanf("%s",write_msg1);
  23. printf("Enter the msg sent from child to child1:");
  24. scanf("%s",write_msg2);
  25.  
  26.  
  27. pid_t pid_child;
  28. pid_child = fork();
  29.  
  30. if(pid_child<0){printf("ERROR IN CHILD\n");return 1;}
  31. else if (pid_child==0){
  32. printf("WE ARE IN CHILD \n");
  33.  
  34.  
  35. close(pipefd1[1]); // close writing
  36. read(pipefd1[0],read_msg1,sizeof(read_msg1));
  37. printf("THE MSG FROM PARENT IS :%s \n", read_msg1);
  38. close(pipefd1[0]);
  39.  
  40.  
  41. close(pipefd2[0]);
  42. write(pipefd2[1],write_msg2,strlen(write_msg2)+1);
  43. printf("MSG SENT TO CHILD1 IS :%s \n", write_msg2);
  44. close(pipefd2[1]);
  45.  
  46.  
  47. pid_t pid_child1;
  48. pid_child1 = fork();
  49.  
  50. if(pid_child1<0){printf("ERROR IN CHILD1\n");return 1;}
  51. else if (pid_child1==0){
  52. printf("WE ARE IN CHILD 1");
  53.  
  54.  
  55. close(pipefd2[1]); // close writing
  56. read(pipefd2[0],read_msg2,sizeof(read_msg2));
  57. printf("THE MSG FROM CHILD IS :%s \n", read_msg2);
  58. close(pipefd2[0]);
  59.  
  60.  
  61. }else { wait(NULL); }
  62.  
  63.  
  64.  
  65. }else {
  66.  
  67. printf("WE ARE IN PARENT\n");
  68.  
  69.  
  70. close(pipefd1[0]);
  71. write(pipefd1[1],write_msg1,strlen(write_msg1)+1);
  72. printf("MSG SENT TO CHILD IS :%s \n", write_msg1);
  73. close(pipefd1[1]);
  74.  
  75. wait(NULL);
  76.  
  77. }
  78.  
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
Enter the msg sent from parent to child:Enter the msg sent from child to child1:WE ARE IN CHILD 
THE MSG FROM PARENT IS :p��Y� 
MSG SENT TO CHILD1 IS :�2�q 
WE ARE IN CHILD 1THE MSG FROM CHILD IS : 
Enter the msg sent from parent to child:Enter the msg sent from child to child1:WE ARE IN CHILD 
THE MSG FROM PARENT IS :p��Y� 
MSG SENT TO CHILD1 IS :�2�q 
Enter the msg sent from parent to child:Enter the msg sent from child to child1:WE ARE IN PARENT
MSG SENT TO CHILD IS :p��Y�