Guest User

Untitled

a guest
Jul 22nd, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using std::cout;
  5. using std::cerr;
  6. using std::endl;
  7. int MAXLINE = 9000;
  8.  
  9. //ps -A | grep argv[1] | wc -l
  10. int main(int argc, const char* argv[]) {
  11. int pid, char_count, ps_pipes[2], wc_pipes[2];
  12. char line[MAXLINE];
  13.  
  14. if (argc != 2) {
  15. cerr << "Error: invalid number of arguments (" << argc << "). Expecting 2" << endl;
  16. return 1;
  17. }
  18.  
  19. //The commands are forked in reverse order wc -> grep -> ps
  20.  
  21. //create the pipe
  22. if (pipe(ps_pipes) < 0 && pipe(wc_pipes) < 0) {
  23. cerr << "Pipe error" << endl;
  24. return -1;
  25. }
  26.  
  27. pid = fork();//child forked for grep
  28.  
  29. if (pid < 0) {
  30. cerr << "First Fork error" << endl;
  31. return -1;
  32. }
  33.  
  34. //Parent (wc -l)
  35. if (pid > 0) {
  36. wait();//Have to wait for grep to finish
  37.  
  38. close(wc_pipes[1]);//close the write pipe, this should write to stdout
  39.  
  40. dup2(wc_pipes[0], 0);//set the stdin of the process to the read pipe
  41.  
  42. execlp("wc", "wc", "-l", (char*)0);//Replace the process
  43.  
  44. } else { //Child (grep argv[1])
  45.  
  46. pid = fork();//child forked for ps
  47.  
  48. if (pid < 0) {
  49. cerr << "Second Fork error" << endl;
  50. return -1;
  51. }
  52.  
  53. //In main child (grep argv[1])
  54. if (pid > 0) { //in parent (grep argv[1])
  55. wait();
  56.  
  57. close(ps_pipes[1]);//close the write pipe from ps. grep will write to wc_pipes
  58. close(wc_pipes[0]);
  59.  
  60. dup2(ps_pipes[0], 0);//set the stdin of the process to the read pipe
  61. dup2(wc_pipes[1], 1);//set the stdout of the process to go to wc
  62.  
  63. execlp("grep", "grep", argv[1], (char*)0);//Replace the process
  64.  
  65.  
  66. } else {//Grand-Child (ps -A)
  67. close(ps_pipes[0]);//close the read pipe. ps won't be reading
  68.  
  69. dup2(ps_pipes[1], 1);//set the stdout of the process to go to grep
  70.  
  71. execlp("ps", "ps", "-A", (char*)0);//Replace the process
  72. }
  73. }
  74. exit(0);
  75. }
Add Comment
Please, Sign In to add comment