Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.61 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8.  
  9. enum { STD_IN = 0, STD_OUT = 1 };
  10.  
  11. int main (int argc, char* argv[])
  12. {
  13.     int f[2], status;
  14.     pid_t pid;
  15.     if (pipe(f) == -1)
  16.     {
  17.         exit(1);
  18.     }
  19.     if (!(pid = fork())) {
  20.         close(f[0]);
  21.         dup2(f[1],STD_OUT);
  22.         close(f[1]);
  23.         if (!(pid = fork())) {
  24.             int fd = open(argv[4],O_RDONLY,0);
  25.             if (fd == -1) {
  26.                 exit(1);
  27.             }
  28.             if (dup2(fd,STD_IN) == -1) {
  29.                 exit(1);
  30.             }
  31.             close(fd);
  32.             execlp(argv[1], argv[1], NULL);
  33.             exit(1);
  34.         } else if (pid == -1) {
  35.             exit(1);
  36.         } else {
  37.             wait(&status);
  38.             if (WIFEXITED(status) && !WEXITSTATUS(status)) {
  39.                 execlp(argv[2], argv[2], NULL);
  40.                 exit(1);
  41.             }
  42.             close(f[1]);
  43.             wait(&status);
  44.             exit(0);
  45.         }
  46.     }
  47.     if (!(pid = fork())) {
  48.         close(f[1]);
  49.         dup2(f[0],STD_IN);
  50.         close(f[0]);
  51.         int fd = open(argv[5],O_WRONLY|O_CREAT|O_APPEND,0660);
  52.         if (fd == -1) {
  53.             exit(1);
  54.         }
  55.         if (dup2(fd,STD_OUT) == -1) {
  56.             exit(1);
  57.         }
  58.         close(fd);
  59.         execlp(argv[3], argv[3], NULL);
  60.         exit(1);
  61.     } else if (pid == -1) {
  62.         exit(1);
  63.     } else {
  64.         close(f[0]);
  65.         close(f[1]);
  66.         wait(&status);
  67.         wait(&status);
  68.         exit(0);
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement