ar@cello ~ % cat crustaceae.c #include #include #include #include int do_son(int i, int inbound, int outbound) { char buf[8]; int k; read(inbound, buf, 1); // lock read(0, buf, 8); sscanf(buf, "%d", &k); write(outbound, buf, 1); // unlock printf("%d %d\n", i + 1, k * k); return 0; } int main (int argc, char **argv) { char token[1] = {' '}; char buf[24]; int f2s[2]; int s2f[2]; pid_t pid[3]; int status = 0; if(pipe(f2s) < 0) { fprintf(stderr, "%s: %s\n", argv[0], "Could not pipe"); return 1; } if(pipe(s2f) < 0) { fprintf(stderr, "%s: %s\n", argv[0], "Could not pipe"); return 1; } for(int i = 0; i < 3; i++) { pid[i] = fork(); if(pid[i] < 0) { fprintf(stderr, "%s: %s\n", argv[0], "Could not fork"); return 1; } if(pid[i] == 0) { close(f2s[1]); close(s2f[0]); return do_son(i, f2s[0], s2f[1]); } } close(f2s[0]); close(s2f[1]); for(int i = 0; i < 3; i++) { /* Let's make a request... */ write(f2s[1], token, 1); /* ...and wait for the response */ read(s2f[0], token, 1); } for(int i = 0; i < 3; i++) { wait(&status); } close(f2s[1]); close(s2f[0]); return 0; } ar@cello ~ % gcc crustaceae.c -o crustaceae ar@cello ~ % printf '-0036 \n 506 \n -40\n' | ./crustaceae 3 1296 1 256036 2 1600 ar@cello ~ % printf '-0036 \n 506 \n -40\n' | ./crustaceae 2 1296 1 256036 3 1600 ar@cello ~ % printf '-0036 \n 506 \n -40\n' | ./crustaceae 1 1296 3 256036 2 1600 ar@cello ~ %