Guest User

Untitled

a guest
Dec 10th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <sys/wait.h>
  6.  
  7. int main(int argc, char **argv)
  8. {
  9. int pipefd[2];
  10. int second_pipefd[2];
  11. int childpid1, childpid2, childpid3;
  12. int exit_code1, exit_code2;
  13. char *cmd[3] = {"ls", NULL, NULL};
  14. char *cmd2[3] = {"grep", ".c", NULL};
  15. char *cmd3[3] = {"wc", NULL, NULL};
  16. pipe(pipefd);
  17. pipe(second_pipefd);
  18.  
  19. childpid1 = fork();
  20. if (childpid1 == 0)
  21. {
  22. close(STDOUT_FILENO);
  23. dup2(pipefd[1], STDOUT_FILENO);
  24. close(pipefd[1]);
  25. execvp("ls", cmd);
  26.  
  27. _exit(0);
  28. }
  29. close(pipefd[1]);
  30.  
  31. /* if not closing this end there is a dead-lock when awaiting child */
  32. childpid2 = fork();
  33. if (childpid2 == 0)
  34. {
  35. close(STDIN_FILENO);
  36. dup2(pipefd[0], STDIN_FILENO);
  37. close(pipefd[0]);
  38.  
  39. close(STDOUT_FILENO);
  40. dup2(second_pipefd[1], STDOUT_FILENO);
  41. close(second_pipefd[1]);
  42.  
  43. execvp("grep", cmd2);
  44.  
  45. _exit(0);
  46. }
  47. /* if not closing this end there is a dead-lock when awaiting child */
  48. close(pipefd[0]);
  49. close(second_pipefd[1]);
  50.  
  51. childpid3 = fork();
  52. if (childpid3 == 0)
  53. {
  54. close(STDIN_FILENO);
  55. dup2(second_pipefd[0], STDIN_FILENO);
  56. close(second_pipefd[0]);
  57. execvp("wc", cmd3);
  58.  
  59. _exit(0);
  60. }
  61. close(second_pipefd[0]);
  62.  
  63. /* If not waiting and closing pipe - the procs wont exit but
  64. the main proc will continue */
  65. waitpid(childpid1, &exit_code1, 0);
  66. waitpid(childpid2, &exit_code2, 0);
  67. waitpid(childpid3, &exit_code2, 0);
  68.  
  69. return 0;
  70. }
Add Comment
Please, Sign In to add comment