Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.80 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <unistd.h>
  3.  
  4. int pid;
  5. int pipe1[2];
  6. int pipe2[2];
  7.  
  8. void main() {
  9.  
  10.   // create pipe1
  11.   if (pipe(pipe1) == -1) {
  12.     perror("bad pipe1");
  13.     exit(1);
  14.   }
  15.  
  16.   // fork (ps aux)
  17.   if ((pid = fork()) == -1) {
  18.     perror("bad fork1");
  19.     exit(1);
  20.   } else if (pid == 0) {
  21.     // stdin --> ps --> pipe1
  22.     exec1();
  23.   }
  24.   // parent
  25.  
  26.   // create pipe2
  27.   if (pipe(pipe2) == -1) {
  28.     perror("bad pipe2");
  29.     exit(1);
  30.   }
  31.  
  32.   // fork (grep root)
  33.   if ((pid = fork()) == -1) {
  34.     perror("bad fork2");
  35.     exit(1);
  36.   } else if (pid == 0) {
  37.     // pipe1 --> grep --> pipe2
  38.     exec2();
  39.   }
  40.   // parent
  41.  
  42.   // close unused fds
  43.   close(pipe1[0]);
  44.   close(pipe1[1]);
  45.  
  46.   // fork (grep sbin)
  47.   if ((pid = fork()) == -1) {
  48.     perror("bad fork3");
  49.     exit(1);
  50.   } else if (pid == 0) {
  51.     // pipe2 --> grep --> stdout
  52.     exec3();
  53.   }
  54.   // parent
  55.  
  56.  
  57. }
  58.  
  59. void exec1() {
  60.   // input from stdin (already done)
  61.   // output to pipe1
  62.   dup2(pipe1[1], 1);
  63.   // close fds
  64.   close(pipe1[0]);
  65.   close(pipe1[1]);
  66.   // exec
  67.   execl("/bin/ls","bin/ls", "-l","-a", "dev", NULL);
  68.   // exec didn't work, exit
  69.   wait(NULL);
  70.   perror("bad exec ls");
  71.   _exit(1);
  72. }
  73.  
  74. void exec2() {
  75.   // input from pipe1
  76.   dup2(pipe1[0], 0);
  77.   // output to pipe2
  78.   dup2(pipe2[1], 1);
  79.   // close fds
  80.   close(pipe1[0]);
  81.   close(pipe1[1]);
  82.   close(pipe2[0]);
  83.   close(pipe2[1]);
  84.   // exec
  85.   execlp("sort","sort", NULL);
  86.   // exec didn't work, exit
  87.   wait(NULL);
  88.   perror("bad exec sort");
  89.   _exit(1);
  90. }
  91.  
  92. void exec3() {
  93.   // input from pipe2
  94.   dup2(pipe2[0], 0);
  95.   // output to stdout (already done)
  96.   // close fds
  97.   close(pipe2[0]);
  98.   close(pipe2[1]);
  99.   // exec
  100.   execlp("more","more", NULL);
  101.   wait(NULL);
  102.   // exec didn't work, exit
  103.   perror("bad exec more");
  104.   _exit(1);
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement