// // // // // // // // // // // // // // // // // // // // // // // // // // CS270 Class Example // // Author: Robert Heckendorn // University of Idaho // #include #include // for system #include // for open and open flags #include // for errno #include // for strerror #include // for unlink int main() { pid_t pid; int pipefds[2]; char *whoAmI; printf("\nBEGINNING TESTS\n"); fflush(stdout); // open a pipe if (pipe(pipefds)==-1) { printf("ERROR: pipe failure\n"); fflush(stdout); } else { // pipe is up and running so... fork pid = fork(); switch (pid) { case -1: perror("ERROR: Fork failed"); exit(1); // CHILD case 0: { // local data int data3size=1024; char data3[data3size]; int len; whoAmI = (char *)"Child"; sleep(3); printf("%s: Start reading from %d\n", whoAmI, pipefds[0]); fflush(stdout); // read from fds[0] if ((len = read(pipefds[0], data3, data3size))==-1) { printf("ERROR: receiver trying to read from fd: %d\n", pipefds[0]); } else { printf("%s read %d bytes\n", whoAmI, len); printf("%s: DATA:", whoAmI); // fflush(stdout); write(1, data3, len); // use printf. printf("\n"); } } break; default: { // local variables char *data = (char *)"Now is the winter of our discontent made glorious summer by this sun of York"; char *data2 = (char *)"Cry havoc and let slip the dogs of war."; whoAmI = (char *)"Parent"; // sleep(2); // write to fds[1] write(pipefds[1], data, strlen(data)); printf("%s: writes %d bytes of data to fd: %d\n", whoAmI, (int)strlen(data), pipefds[1]); fflush(stdout); write(pipefds[1], data2, strlen(data2)); printf("%s: writes %d bytes of data to fd: %d\n", whoAmI, (int)strlen(data2), pipefds[1]); fflush(stdout); printf("%s: done writing\n", whoAmI); fflush(stdout); // sleep(5); { int stat_val; printf("Parent waiting on child!\n"); wait(&stat_val); // note pass in the address of stat_val if (WIFEXITED(stat_val)) { printf("Parent reports child (PID: %d) exited with return code %d\n", pid, WEXITSTATUS(stat_val)); } else { printf("Parent reports child (PID: %d) terminated abnormally\n", pid); } } break; } } printf("%s: terminates\n", whoAmI); fflush(stdout); return(0); } }