Advertisement
Guest User

conveyor-Program microshell pipe

a guest
Oct 17th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.10 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(int argc, char **argv) {
  5.   int **pfd = malloc((argc - 1) * sizeof(int*));
  6.   if (pfd == NULL) {
  7.     perror("malloc");
  8.     exit(1);
  9.   }
  10.   for (int i = 0; i < argc - 1; ++i) {
  11.     pfd[i] = malloc(2 * sizeof(int));
  12.     if (pfd[i] == NULL) {
  13.       perror("malloc");
  14.       exit(1);
  15.     }
  16.   }
  17.   int f;
  18.   int in = 0;
  19.   for (int i = 0; i < argc - 2; ++i) {
  20.     pipe(pfd[i]);
  21.   }
  22.   for (int i = 1; i < argc; i++) {
  23.     switch (f = fork()) {
  24.     case -1:
  25.       perror("fork");
  26.       exit(1);
  27.       break;
  28.     case 0:
  29.       if (i == 1) {
  30.         dup2(pfd[i - 1][1], 1);
  31.       }
  32.       else {
  33.         dup2(pfd[i - 1][1], 1);
  34.         dup2(pfd[i - 2][0], 0);
  35.       }
  36.       for (int j = 0; j < argc - 2; ++j) {
  37.         close(pfd[j][0]);
  38.         close(pfd[j][1]);
  39.       }
  40.       if (execlp(argv[i], argv[i], NULL) == -1) {
  41.         perror("execlp");
  42.         exit(1);
  43.       }
  44.     }
  45.   }
  46.   for (int i = 0; i < argc - 2; ++i) {
  47.     close(pfd[i][0]);
  48.     close(pfd[i][1]);
  49.   }
  50.   for (int i = 1; i < argc; ++i) {
  51.     wait(NULL);
  52.   }
  53.   return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement