Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <errno.h>
  6. #include <sys/wait.h>
  7.  
  8. #define R_FILE "/proc/meminfo"
  9. #define GREP_EXEC "/bin/grep"
  10. #define SORT_EXEC "/bin/sort"
  11. #define HEAD_EXEC "/usr/bin/head"
  12. #define BSIZE 256
  13.  
  14. int main()
  15. {
  16.     int status;
  17.     pid_t pid_1, pid_2, pid_3;
  18.  
  19.     int pipe1[2], pipe2[2];
  20.  
  21.     if (pipe(pipe1) || pipe(pipe2))
  22.     {
  23.        printf("Error with pipes.\n");
  24.        return -1;
  25.     }
  26.  
  27.     pid_1 = fork();
  28.     if (pid_1 == 0)
  29.     {
  30.       close(pipe1[0]);
  31.       close(pipe2[0]);
  32.       close(pipe2[1]);
  33.       dup2(pipe1[1], STDOUT_FILENO);
  34.  
  35.         /* grep process */
  36.       execl(GREP_EXEC, "grep", "-cr", "Thread", "nachos/", (char *) 0);
  37.      
  38.     return 0;
  39.     }
  40.  
  41.     pid_2 = fork();
  42.     if (pid_2 == 0)
  43.     {
  44.       close(pipe1[1]);
  45.       close(pipe2[0]);
  46.       dup2(pipe1[0], STDIN_FILENO);
  47.       dup2(pipe2[1], STDOUT_FILENO);
  48.      
  49.         /* sort process */
  50.       execl(SORT_EXEC, "sort", "-t", ":", "+1.0", "-2.0", "--numeric", "--reverse", (char *) 0);
  51.         return 0;
  52.     }
  53.  
  54.     pid_3 = fork();
  55.     if (pid_3 == 0)
  56.     {
  57.       close(pipe1[0]);
  58.       close(pipe1[1]);
  59.       close(pipe2[1]);
  60.       dup2(pipe2[0], STDIN_FILENO);
  61.  
  62.         /* head process */
  63.       execl(HEAD_EXEC, "head", "--lines=5", (char *) 0);
  64.         return 0;
  65.     }
  66.  
  67.     /* shell process */
  68.     /* Remember to close unused pipes! */
  69.     close(pipe1[0]);
  70.     close(pipe1[1]);
  71.     close(pipe2[0]);
  72.     close(pipe2[1]);
  73.     close(STDIN_FILENO);
  74.     close(STDOUT_FILENO);
  75.  
  76.     if ((waitpid(pid_1, &status, 0)) == -1)
  77.     {
  78.         fprintf(stderr, "Process 1 encountered an error. ERROR%d", errno);
  79.         return EXIT_FAILURE;
  80.     }        
  81.  
  82.     if ((waitpid(pid_2, &status, 0)) == -1)
  83.     {
  84.         fprintf(stderr, "Process 2 encountered an error. ERROR%d", errno);
  85.         return EXIT_FAILURE;
  86.     }
  87.  
  88.     if ((waitpid(pid_3, &status, 0)) == -1)
  89.     {
  90.         fprintf(stderr, "Process 3 encountered an error. ERROR%d", errno);
  91.         return EXIT_FAILURE;
  92.     }
  93.    
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement