#include #include #include #include #include #include "args.h" int readline (int fd, stralloc * sa) { int ret; char c; sa->len = 0; while (1) { ret = read (fd, &c, 1); if (ret < 0) continue; if (ret == 0) break; if (!stralloc_append (sa, &c)) return 0; if (c == '\n') break; } if (sa->len == 0) return 0; return 1; } void reverse (stralloc * sa) { int p, q; char tmp; assert (sa->len); q = sa->len - 1; if (sa->s[q] == '\n') q--; for (p = 0; p < q; ++p, --q) { tmp = sa->s[p]; sa->s[p] = sa->s[q]; sa->s[q] = tmp; } } int main () { int p1[2]; int p2[2]; int pid; stralloc sa = {0}; if (pipe (p1) < 0) { perror ("pipe"); return 1; } if (pipe (p2) < 0) { perror ("pipe"); return 1; } pid = fork (); if (pid < 0) { perror ("fork"); return 1; } if (pid == 0) { /* Child */ dup2 (p1[0], 0); close (p1[0]); close (p1[1]); dup2 (p2[1], 1); close (p2[0]); close (p2[1]); execlp ("tr", "tr", ARG1, ARG2, NULL); perror ("execlp"); return 1; } /* Parent */ pid = fork (); if (pid < 0) { perror ("fork"); return 1; } if (pid > 0) { /* Child */ close (p1[0]); close (p1[1]); close (p2[1]); /* Read lines from p2[0], reverse and write to 1 */ while (readline (p2[0], &sa)) { reverse (&sa); write (1, sa.s, sa.len); } return 0; } /* Parent */ close (p1[0]); close (p2[0]); close (p2[1]); /* Read lines from 0, reverse and write to p1[1] */ while (readline (0, &sa)) { reverse (&sa); write (p1[1], sa.s, sa.len); } return 0; }