uni

University stuff
git clone git://git.christosmarg.xyz/uni-assignments.git
Log | Files | Refs | README | LICENSE

lab2_pipe.c (1796B)


      1 #include <sys/types.h>
      2 #include <sys/stat.h>
      3 #include <sys/wait.h>
      4 
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <string.h>
      8 #include <unistd.h>
      9 
     10 #define DEFPAGER "/usr/bin/less"
     11 
     12 static char *argv0;
     13 
     14 int
     15 main(int argc, char *argv[])
     16 {
     17         FILE *fp;
     18         char buf[BUFSIZ], *pager, *argv0;
     19         pid_t pid;
     20         int fd[2], n;
     21 
     22 	argv0 = *argv;
     23         if (argc != 2) {
     24 		fprintf(stderr, "usage: %s file\n", argv0);
     25 		return 1;
     26 	}
     27         if ((fp = fopen(argv[1], "r")) == NULL)
     28                 err(1, "fopen");
     29         if (pipe(fd) < 0)
     30                 err(1, "pipe");
     31         
     32         switch (pid = fork()) {
     33         case -1:
     34                 err(1, "fork");
     35         case 0:
     36                 close(fd[1]);
     37                 if (fd[0] != STDIN_FILENO) {
     38                         if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO)
     39                                 err(1, "dup2");
     40                         close(fd[0]);
     41                 }
     42                 if ((pager = getenv("PAGER")) == NULL)
     43                         pager = DEFPAGER;
     44                 if ((argv0 = strrchr(pager, '/')) != NULL)
     45                         argv0++;
     46                 else
     47                         argv0 = pager;
     48                 if (execlp(pager, argv0, NULL) < 0)
     49                         err(1, "execlp");
     50         default:
     51                 close(fd[0]);
     52                 while (fgets(buf, BUFSIZ, fp) != NULL) {
     53                         n = strlen(buf);
     54                         if (write(fd[1], buf, n) != n)
     55                                 err(1, "write");
     56                 }
     57                 if (ferror(fp))
     58                         err(1, "fgets");
     59                 close(fd[1]);
     60                 if (waitpid(pid, NULL, 0) < 0)
     61                         err(1, "waitpid");
     62                 exit(0);
     63         }
     64 
     65         return 0;
     66 }