#include #include #include #include #include #include void sigpipe_handler(int dummy) { printf("Pid %d: Caught sigpipe\n", getpid()); exit(1); } #define BSIZE 16000 main(int argc, char **argv) { int p[2]; int id, i, j; char s[BSIZE]; FILE *f; signal(SIGPIPE, sigpipe_handler); if (argc != 3) { fprintf(stderr, "usage: q4 command-string-1 command-string2\n"); exit(1); } pipe(p); id = fork(); if (id == 0) { id = 1; f = fopen("OC.txt", "w"); printf("Child is pid %d\n", getpid()); } else { id = 2; f = fopen("OP.txt", "w"); printf("Parent is pid %d\n", getpid()); } for (i = 0; argv[id][i] != '\0'; i++) { /* printf("%d: %c\n", id, argv[id][i]); */ if (argv[id][i] == 'A') close(p[0]); if (argv[id][i] == 'B') close(p[1]); if (argv[id][i] == 'C') { for (j = 0; j < BSIZE-2; j++) s[j] = 'A'; s[BSIZE-1] = '\n'; j = write(p[1], s, BSIZE); } if (argv[id][i] == 'D') { j = read(p[0], s, BSIZE); if (j != BSIZE) { printf("Pid %d: Exit on read from p[0]\n", getpid()); exit(1); } fwrite(s, 1, BSIZE, f); fflush(f); } if (argv[id][i] == 'S') sleep(1); } printf("Pid %d: Normal Exit\n", getpid()); exit(0); }