Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6.  
  7. #define CHILDREN 3
  8.  
  9. int main(void)
  10. {
  11.   pid_t p[CHILDREN];
  12.   int fd[CHILDREN - 1][2];
  13.  
  14.   int i;
  15.   for (i = 0; i < CHILDREN - 1; i++)
  16.   {
  17.     if (pipe(fd[i]) == -1)
  18.     {
  19.       perror("pipe failed\n");
  20.       return 1;
  21.     }
  22.   }
  23.  
  24.   for (i = 0; i < CHILDREN; i++)
  25.   {
  26.     p[i] = fork();
  27.     if (p[i] < 0)
  28.     {
  29.       perror("fork failed\n");
  30.       exit(-1);
  31.     }
  32.     if (p[i] == 0)
  33.       break;
  34.   }
  35.  
  36.   switch (i)
  37.   {
  38.   // Filho 1
  39.   case 0:
  40.     close(fd[0][0]);
  41.     close(fd[1][0]);
  42.     close(fd[1][1]);
  43.  
  44.     // Output para pipe
  45.     dup2(fd[0][1], 1);
  46.  
  47.     close(fd[0][1]);
  48.  
  49.     execlp("ls", "ls", "-la", (char *)NULL);
  50.     perror("error executing 'ls -la'");
  51.     exit(-1);
  52.     break;
  53.   // Filho 2
  54.   case 1:
  55.     close(fd[0][1]);
  56.     close(fd[1][0]);
  57.  
  58.     // Input e output para pipe
  59.     dup2(fd[0][0], 0);
  60.     dup2(fd[1][1], 1);
  61.  
  62.     close(fd[0][0]);
  63.     close(fd[1][1]);
  64.  
  65.     execlp("sort", "sort", NULL);
  66.     perror("error executing 'sort'");
  67.     exit(-1);
  68.     break;
  69.   // Filho 3
  70.   case 2:
  71.     close(fd[0][0]);
  72.     close(fd[1][1]);
  73.     close(fd[0][1]);
  74.  
  75.     dup2(fd[1][0], 0);
  76.  
  77.     close(fd[1][0]);
  78.  
  79.     execlp("wc", "wc", "-l", (char *)NULL);
  80.     perror("error executing 'wc -l'");
  81.     exit(-1);
  82.     break;
  83.   // Pai
  84.   case CHILDREN:
  85.     for (i = 0; i < CHILDREN - 1; i++)
  86.     {
  87.       close(fd[i][0]);
  88.       close(fd[i][1]);
  89.     }
  90.  
  91.     for (i = 0; i < CHILDREN; i++)
  92.       wait(NULL);
  93.     break;
  94.   default:
  95.     printf("Something went wrong.\n");
  96.   }
  97.   return 0;
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement