/************************************************************************ * * * Copyright Digital Equipment Corporation 1998. All rights reserved. * * * * Restricted Rights: Use, duplication, or disclosure by the U.S. * * Government is subject to restrictions as set forth in subparagraph * * (c) (1) (ii) of DFARS 252.227-7013, or in FAR 52.227-19, or in FAR * * 52.227-14 Alt. III, as applicable. * * * * This software is proprietary to and embodies the confidential * * technology of Digital Equipment Corporation. Possession, use, or * * copying of this software and media is authorized only pursuant to a * * valid written license from Digital or an authorized sublicensor. * * * ************************************************************************/ /* chap_5_pipe.c */ /* In this example, the parent writes a string to the pipe for */ /* the child to read. The child then writes the string back */ /* to the pipe for the parent to read. The wait function is */ /* called before the parent reads the string that the child has */ /* passed back through the pipe. Otherwise, the reads and */ /* writes will not be synchronized. */ #include #include #include #include #include #include #include #define inpipe 11 #define outpipe 12 const char *child_name = "chap_5_pipe_child.exe" ; main() { int pipes[2]; int mode, status, cstatus, len; char *outbuf, *inbuf; if ((outbuf = malloc(512)) == 0) { printf("Parent - Outbuf allocation failed\n"); exit(EXIT_FAILURE); } if ((inbuf = malloc(512)) == 0) { printf("Parent - Inbuf allocation failed\n"); exit(EXIT_FAILURE); } if (pipe(pipes) == -1) { printf("Parent - Pipe allocation failed\n"); exit(EXIT_FAILURE); } dup2(pipes[0], inpipe); dup2(pipes[1], outpipe); strcpy(outbuf, "This is a test of two-way pipes.\n"); status = vfork(); switch (status) { case 0: printf("Parent - Starting child\n"); if ((status = execl(child_name, 0)) == -1) { printf("Parent - Exec failed"); exit(EXIT_FAILURE); } break; case -1: printf("Parent - Child process failed\n"); break; default: printf("Parent - Writing to child\n"); if (write(outpipe, outbuf, strlen(outbuf) + 1) == -1) { perror("Parent - Write failed"); exit(EXIT_FAILURE); } else { if ((status = wait(&cstatus)) == -1) perror("Parent - Wait failed"); if (cstatus == CLI$_IMAGEFNF) printf("Parent - Child does not exist\n"); else { printf("Parent - Reading from child\n"); if ((len = read(inpipe, inbuf, 512)) <= 0) { perror("Parent - Read failed"); exit(EXIT_FAILURE); } else { printf("Parent: %s\n", inbuf); printf("Parent - Child final status: %d\n", cstatus); } } } break; } }