Advertisement
danielhilst

pipe.c

Oct 23rd, 2014
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. #include <errno.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8.  
  9. #define STDOUT 1
  10. #define STDERR 2
  11.  
  12. int main(int argc, char **argv)
  13. {
  14.         pid_t pid;
  15.  
  16.         if (argc < 2) {
  17.                 fprintf(stderr, "Usage: %s command args ...\n", argv[0]);
  18.                 exit(EXIT_FAILURE);
  19.         }
  20.  
  21.         pid = fork();
  22.         if (pid == 0) {         /* child */
  23.                 int bout, berr; /* backup stdout and stderr */
  24.                 int rval;
  25.                 int fd = open("output", O_APPEND | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
  26.                 if (fd < 0) {
  27.                         fprintf(stderr, "Error: open %s\n", strerror(errno));
  28.                         exit(EXIT_FAILURE);
  29.                 }
  30.  
  31.                 bout = dup(STDOUT);
  32.                 berr = dup(STDERR);
  33.                 if (bout == -1 ||
  34.                     berr == -1)
  35.                 {
  36.                         fprintf(stderr, "Error: dup (STDOUT|STDERR) %s\n", strerror(errno));
  37.                         exit(EXIT_FAILURE);                        
  38.                 }
  39.  
  40.                 rval = dup2(fd, STDOUT);
  41.                 if (rval < 0) {
  42.                         fprintf(stderr, "Error: dup2 (STDOUT) %s\n", strerror(errno));
  43.                         exit(EXIT_FAILURE);
  44.                 }
  45.  
  46.                 rval = dup2(fd, STDERR);
  47.                 if (rval < 0) {
  48.                         fprintf(stderr, "Error: dup2 (STDERR) %s\n", strerror(errno));
  49.                         exit(EXIT_FAILURE);
  50.                 }
  51.  
  52.                 argv++;
  53.                 rval = execv(argv[0], argv);
  54.                 if (rval == -1) {
  55.                         char message[256];
  56.  
  57.                         snprintf(message, 256, "Error: execv %s\n", strerror(errno));
  58.                         write(berr, message, strlen(message));
  59.                         exit(EXIT_FAILURE);
  60.                 }
  61.                 return 0;
  62.  
  63.         } else if (pid > 0) {   /* parent */
  64.                 return waitpid(pid);
  65.         } else {                /* fork error */
  66.                 fprintf(stderr, "Error: %s\n", strerror(errno));
  67.                 exit(EXIT_FAILURE);
  68.         }
  69.  
  70.         return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement