fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4.  
  5. // pipe setup for ps -aef | grep 0 | wc -l
  6. int main()
  7. {
  8. static const int READ = 0;
  9. static const int WRITE = 1;
  10. int fd[2][2] = {{0}};
  11. int pid = 0;
  12.  
  13. // last process first: wc -l
  14. pipe(fd[0]);
  15. if ((pid = fork()) == 0)
  16. {
  17. // setup "wc -l"
  18. close(fd[0][WRITE]);
  19. dup2(fd[0][READ], READ);
  20. execlp("wc", "wc", "-l", NULL);
  21. }
  22. // no longer need this
  23. close(fd[0][READ]);
  24.  
  25. // middle process: grep 0
  26. pipe(fd[1]);
  27. if ((pid = fork()) == 0)
  28. {
  29. // setup "grep 1"
  30. close(fd[1][WRITE]);
  31. dup2(fd[0][WRITE], WRITE);
  32. dup2(fd[1][READ], READ);
  33. execlp("grep", "grep", "0", NULL);
  34. }
  35. // no longer need this
  36. close(fd[0][WRITE]);
  37. close(fd[1][READ]);
  38.  
  39. // first process
  40. if ((pid = fork()) == 0)
  41. {
  42. // setup ps -aef
  43. dup2(fd[1][WRITE], WRITE);
  44. execlp("ps", "ps", "-aef", NULL);
  45. }
  46. // no longer need his
  47. close(fd[1][WRITE]);
  48.  
  49. pid = wait(NULL);
  50.  
  51. return 0;
  52. }
Success #stdin #stdout 0.01s 4460KB
stdin
Standard input is empty
stdout
190