Advertisement
cd62131

uniq | wc -l in C using pipe, dup2, fork, execl

Jul 7th, 2017
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.82 KB | None | 0 0
  1. #include <stddef.h>
  2. #include <unistd.h>
  3.  
  4. static void readwrite_pipe(int, int);
  5.  
  6. int main(void) {
  7.   int fd1[2];
  8.   int fd2[2];
  9.   pipe(fd1);
  10.   pipe(fd2);
  11.   if (fork() == 0) {
  12.     dup2(fd1[0], STDIN_FILENO);
  13.     close(fd1[0]);
  14.     close(fd1[1]);
  15.     dup2(fd2[1], STDOUT_FILENO);
  16.     close(fd2[0]);
  17.     close(fd2[1]);
  18.     execl("/usr/bin/uniq", "uniq", NULL);
  19.   } else {
  20.     close(fd1[0]);
  21.     readwrite_pipe(STDIN_FILENO, fd1[1]);
  22.     close(fd1[1]);
  23.     dup2(fd2[0],STDIN_FILENO);
  24.     close(fd2[0]);
  25.     close(fd2[1]);
  26.     execl("/usr/bin/wc", "wc", "-l", NULL);
  27.   }
  28. }
  29.  
  30. static void readwrite_pipe(int in, int out) {
  31.   size_t line_max = sysconf(_SC_LINE_MAX);
  32.   char *buf[line_max];
  33.   for (ssize_t size = read(in, buf, line_max); size > 0; size = read(in, buf, line_max)) {
  34.     write(out, buf, size);
  35.   }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement