Guest User

Untitled

a guest
Dec 11th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7.  
  8. #define MAX_CHILDREN 3
  9.  
  10. int main(int argc, char *argv[])
  11. {
  12. pid_t pid;
  13.  
  14. int fd[2];
  15.  
  16. char buffer[100];
  17.  
  18. char str[] = "Hello";
  19. char str2[] = "Hello2";
  20. char str3[] = "Hello3";
  21.  
  22. for(int num_process = 0; num_process < MAX_CHILDREN; num_process++)
  23. {
  24. if(pipe(fd) == -1)
  25. {
  26. perror( "pipe Failed" );
  27. continue;
  28. }
  29.  
  30. pid = fork();
  31.  
  32. if(pid < 0)
  33. {
  34. perror("fork failed");
  35. exit(1);
  36. }
  37.  
  38. if(pid == 0)
  39. { //child code
  40.  
  41. if(num_process == 0){
  42. printf("Child %i (pid= %i) send string %sn", num_process, getpid(),str);
  43. write(fd[1],str,strlen(str));
  44. }
  45. if(num_process == 1){
  46. printf("Child %i (pid= %i) send string %sn", num_process, getpid(),str2);
  47. write(fd[1],str2,strlen(str2));
  48. }
  49. if(num_process == 2){
  50. printf("Child %i (pid= %i) send string %sn", num_process, getpid(),str3);
  51. write(fd[1],str3,strlen(str3));
  52. }
  53. exit(0);
  54. }
  55.  
  56. else{//parent
  57. printf("Im parent %in",getpid());
  58. wait(NULL);
  59. }
  60. }
  61.  
  62. //Creating another child process from parent, this process recieves string sent from
  63. //childs
  64. pid = fork();
  65.  
  66. if(pid < 0)
  67. {
  68. perror("fork failed");
  69. exit(1);
  70. }
  71. if(pid == 0){//child
  72. printf("The new process %i read fd pipen",getpid());
  73. if( read(fd[0],buffer,sizeof(buffer)) <= 0) //read pipe
  74. {
  75. perror("error read");
  76. exit( EXIT_FAILURE );
  77. }
  78. printf("String readed : %sn",buffer);
  79. }
  80. else{//parent
  81. wait(NULL);
  82. }
  83.  
  84. return 0;
  85. }
Add Comment
Please, Sign In to add comment