Guest User

Untitled

a guest
Nov 18th, 2018
768
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. child 1 start
  2. child 2 start
  3. child 3 start
  4. child 3 read (0), finish
  5.  
  6. child 2 read (0), finish
  7.  
  8. child 1 read (0), finish
  9.  
  10. else {
  11. for (int j = 0; j < i; j++) {
  12. close(childs[j]);
  13. }
  14. close(p[1]);
  15. printf("child %d startn", i + 1);
  16.  
  17. #include <stdlib.h>
  18. #include <stdio.h>
  19. #include <unistd.h>
  20. #include <sys/types.h>
  21. #include <sys/wait.h>
  22.  
  23. int main(int argc, char **argv) {
  24.  
  25. int children_w[3];
  26.  
  27. for (int i = 0; i < 3; ++i) {
  28. int p[2];
  29.  
  30. if (0>pipe(p))
  31. { perror("pipe"); exit(1); }
  32.  
  33. pid_t pid;
  34. if(0> (pid= fork()))
  35. { perror("fork"); exit(1); }
  36.  
  37. if(pid==0) {
  38. /* Fix -- close the leaked write ends */
  39. int j;
  40. for(j=0; j<i; j++)
  41. close(children_w[j]);
  42. /* end fix*/
  43. close(p[1]);
  44. printf("child %d startn", i + 1);
  45.  
  46. char buf[10];
  47. buf[0] = 0;
  48. int r;
  49. if ((r = read(p[0], buf, 9)) == -1) { perror("read");/*...*/ }
  50.  
  51. printf("child %d read %s (%d), finishn", i + 1, buf, r);
  52.  
  53. sleep(2);
  54. exit(0);
  55. }
  56. children_w[i] = p[1];
  57. close(p[0]);
  58. }
  59.  
  60. for (int i = 0; i < 3; ++i) {
  61. // if (argc > 1) {
  62. // write(childs[i], "42", 2);
  63. // }
  64. // ============== HERE >>>
  65. close(children_w[i]);
  66. }
  67.  
  68. pid_t pid;
  69. while ((pid = waitpid(-1, NULL, 0)) > 0) {
  70. printf("child %d exitedn", pid);
  71. }
  72.  
  73. return 0;
  74. }
Add Comment
Please, Sign In to add comment