#include #define oops(m) { perror(m); exit(1); } main() { int p[2]; pipe(p); if ( fork() == 0 ) child(p); parent(p); } /* * child waits for parent message */ child(int p[]) { char x[100]; int n; int k = 0; while(1) { n = read(p[0], x, 100); if ( n == -1 ) oops("read in child"); write(1,"child: ",7); write(1, x, n); sprintf(x, "from child %d\n", k++); if ( write(p[0], x, strlen(x)) == -1 ) oops("write from child"); } } /* * parent writes first message */ parent(int p[]) { char x[100]; int n; int k = 0; while(1) { sprintf(x, "from parent %d\n", k++); if ( write(p[1], x, strlen(x)) == -1 ) oops("write from parent"); n = read(p[1], x, 100); if ( n == -1 ) oops("read in parent"); write(1,"parent: ",9); write(1, x, n); } }