Running stdin/out through a pipe to a child process

Lawrence W. McVoy mcvoy at rsch.WISC.EDU
Wed Jan 14 05:09:39 AEST 1987


In article <136 at cogent.UUCP> mark at cogent.UUCP (Mark Steven Jeghers) writes:
>I need to know how I might create a child process with 2 pipes connected to
>it, one with which the parent process feeds a stream to the childs stdin, 
>and one from which the parent reads a stream from the childs stdout.  I 
>understand how to use popen() to connect either stdin OR stdout between
>processes, but I need to have BOTH.  The following picture demonstrates:
>
>                      +-------------------+
>                      |  Parent Process   |
>                      +-------------------+
>               Pipe that   |         ^ Pipe that
>               feeds stdin V         | reads stdout
>                      +-------------------+
>                      |   Child Process   |
>                      +-------------------+

# include	<stdio.h>
# define	R		0
# define	W		1

main() {
    int	in[2];
    int out[2];

    pipe(in);
    pipe(out);

    if (fork()) {
	/* OK, I'm the parent.  I want to to close the 
	 * read side of in and the write side of out (for tidiness).
	 */
	close(in[R]);
	close(out[W]);
    }
    else {
	/* OK, I'm the child.  I want to set up those pipes to feed 
	 * my stdin & stdout.  The general idea is to close the existing
	 * stdin/out and replace them with pipes.  Also, close the non-used
	 * sides of the pipes.
	 */
	close(in[W]);
	close(out[R]);
# if    BSD && HAVE_DUP2
	dup2(0, in[R]);
	dup2(1, out[W]);
# else
	/* This works because Unix always returns the LOWEST numbered 
	 * file descriptor available. ORDER is important.
	 */
	close(0);
	dup(in[R]);
	close(1);
	dup(out[W]);
# endif
    }
    /* OK, all set: exec or whatever */
}

/* It sounds like you would like to read an advanced unix programming
 * book.  Try this one:
 *
 * Advanced Unix Programming
 * Marc Rochkind
 * Prentice-Hall
 * ISBN 0-13-011800-1
 */
-- 
Larry McVoy 	        mcvoy at rsch.wisc.edu, 
      		        {seismo, topaz, harvard, ihnp4, etc}!uwvax!mcvoy

"They're coming soon!  Quad-stated guru-gates!"



More information about the Comp.unix.wizards mailing list