Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #define CHILDREN 3
- int main(void)
- {
- pid_t p[CHILDREN];
- int fd[CHILDREN - 1][2];
- int i;
- for (i = 0; i < CHILDREN - 1; i++)
- {
- if (pipe(fd[i]) == -1)
- {
- perror("pipe failed\n");
- return 1;
- }
- }
- for (i = 0; i < CHILDREN; i++)
- {
- p[i] = fork();
- if (p[i] < 0)
- {
- perror("fork failed\n");
- exit(-1);
- }
- if (p[i] == 0)
- break;
- }
- switch (i)
- {
- // Filho 1
- case 0:
- close(fd[0][0]);
- close(fd[1][0]);
- close(fd[1][1]);
- // Output para pipe
- dup2(fd[0][1], 1);
- close(fd[0][1]);
- execlp("ls", "ls", "-la", (char *)NULL);
- perror("error executing 'ls -la'");
- exit(-1);
- break;
- // Filho 2
- case 1:
- close(fd[0][1]);
- close(fd[1][0]);
- // Input e output para pipe
- dup2(fd[0][0], 0);
- dup2(fd[1][1], 1);
- close(fd[0][0]);
- close(fd[1][1]);
- execlp("sort", "sort", NULL);
- perror("error executing 'sort'");
- exit(-1);
- break;
- // Filho 3
- case 2:
- close(fd[0][0]);
- close(fd[1][1]);
- close(fd[0][1]);
- dup2(fd[1][0], 0);
- close(fd[1][0]);
- execlp("wc", "wc", "-l", (char *)NULL);
- perror("error executing 'wc -l'");
- exit(-1);
- break;
- // Pai
- case CHILDREN:
- for (i = 0; i < CHILDREN - 1; i++)
- {
- close(fd[i][0]);
- close(fd[i][1]);
- }
- for (i = 0; i < CHILDREN; i++)
- wait(NULL);
- break;
- default:
- printf("Something went wrong.\n");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement