Advertisement
wowonline

Untitled

Nov 28th, 2021
742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <fcntl.h>
  3. #include <sys/wait.h>
  4.  
  5. int
  6. main(int argc, char *argv[])
  7. {
  8.     pid_t pid;
  9.     int fd, status;
  10.     int fds[2];
  11.     if (pipe(fds) == -1) {
  12.         return 1;
  13.     }
  14.  
  15.     pid = fork();
  16.     if (pid == -1) {
  17.         return 1;
  18.     } else if (!pid) {
  19.         if (close(fds[0]) == -1) {
  20.             _exit(1);
  21.         }
  22.         fd = open(argv[4], O_RDONLY);
  23.         if (fd == -1) {
  24.             _exit(1);
  25.         }
  26.         if (dup2(fd, 0) == -1) {
  27.             _exit(1);
  28.         }
  29.         if (dup2(fds[1], 1) == -1) {
  30.             _exit(1);
  31.         }
  32.         execlp(argv[1], argv[1], NULL);
  33.         close(fds[1]);
  34.         _exit(1);
  35.     }
  36.     if (wait(&status) == -1) {
  37.         return 1;
  38.     }
  39.    
  40.     if (WIFEXITED(status) && !WEXITSTATUS(status)) {
  41.         pid = fork();
  42.         if (pid == -1) {
  43.             return 1;
  44.         } else if (!pid) {
  45.             if (close(fds[0]) == -1) {
  46.                 _exit(1);
  47.             }
  48.             if (dup2(fds[1], 1) == -1) {
  49.                 _exit(1);
  50.             }
  51.             execlp(argv[2], argv[2], NULL);
  52.             close(fds[1]);
  53.             _exit(1);
  54.         }
  55.         if (wait(NULL) == -1) {
  56.             return 1;
  57.         }
  58.     }
  59.  
  60.     pid = fork();
  61.     if (pid == -1) {
  62.         return 1;
  63.     } else if (!pid) {
  64.         fd = open(argv[5], O_CREAT | O_WRONLY | O_APPEND, 0777);
  65.         if (fd == -1) {
  66.             _exit(1);
  67.         }
  68.         if (dup2(fds[0], 0) == -1) {
  69.             _exit(1);
  70.         }
  71.         if (dup2(fds[1], 1) == -1) {
  72.             _exit(1);
  73.         }
  74.         execlp(argv[3], argv[3], NULL);
  75.         close(fds[0]);
  76.         close(fds[1]);
  77.         _exit(1);
  78.     }
  79.  
  80.     if (wait(NULL) == -1) {
  81.         return 1;
  82.     }
  83.     if (close(fds[0]) == -1) {
  84.         return 1;
  85.     }
  86.     if (close(fds[1]) == -1) {
  87.         return 1;
  88.     }
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement