Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <wait.h>
- int create_childs(int amount) {
- pid_t pid;
- int i;
- for (i = 0; i < amount; i++) {
- pid = fork();
- if (pid == 0) {
- return i; // Filhos
- } else if (pid < 0) {
- puts("Erro ao fazer fork");
- exit(-1);
- }
- }
- return amount; // Pai
- }
- void duplicate(int descriptor1, int descriptor2) {
- if (dup2(descriptor1, descriptor2) == -1) {
- puts("Nao foi possivel trocar o descritor");
- exit(-1);
- }
- }
- void close_descriptor(int descriptor) {
- if (close(descriptor) == -1) {
- printf("Nao foi possivel fechar o pipe %d\n", descriptor);
- exit(-1);
- }
- }
- void create_pipe(int fd[2]) {
- if (pipe(fd) == -1) {
- puts("Erro ao criar o pipe");
- exit(-1);
- }
- }
- void ls(int ls_to_sort[2], int sort_to_wc[2]) {
- close_descriptor(ls_to_sort[0]);
- close_descriptor(sort_to_wc[0]);
- close_descriptor(sort_to_wc[1]);
- duplicate(ls_to_sort[1], fileno(stdout));
- if (execlp("ls", "ls", "-la", (char *) NULL) == -1) {
- puts("O exec do ls não teve sucesso");
- }
- close_descriptor(ls_to_sort[1]);
- }
- void sort(int ls_to_sort[2], int sort_to_wc[2]) {
- close_descriptor(ls_to_sort[1]);
- close_descriptor(sort_to_wc[0]);
- duplicate(ls_to_sort[0], fileno(stdin));
- duplicate(sort_to_wc[1], fileno(stdout));
- if (execlp("sort", "sort", (char *) NULL) == -1) {
- puts("O exec do sort não teve sucesso");
- }
- close_descriptor(sort_to_wc[1]);
- close_descriptor(ls_to_sort[0]);
- }
- void wc(int ls_to_sort[2], int sort_to_wc[2]) {
- close_descriptor(ls_to_sort[0]);
- close_descriptor(ls_to_sort[1]);
- close_descriptor(sort_to_wc[1]);
- duplicate(sort_to_wc[0], fileno(stdin));
- if (execlp("wc", "wc", "-l", (char *) NULL) == -1) {
- puts("O exec do wc não teve sucesso");
- }
- close_descriptor(sort_to_wc[0]);
- }
- int main() {
- int id, ls_to_sort[2], sort_to_wc[2];
- create_pipe(ls_to_sort);
- create_pipe(sort_to_wc);
- id = create_childs(2);
- switch (id) {
- case 0:
- ls(ls_to_sort, sort_to_wc);
- break;
- case 1:
- sort(ls_to_sort, sort_to_wc);
- break;
- case 2:
- wc(ls_to_sort, sort_to_wc);
- break;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement