Running stdin/out through a pipe to a child process

Mike McNally m5d at bobkat.UUCP
Sat Jan 17 03:11:55 AEST 1987


In article <3112 at rsch.WISC.EDU> mcvoy at rsch.WISC.EDU (Lawrence W. McVoy) writes:
>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, ......
>
># include	<stdio.h>
>       .
>       .
>       .
># if    BSD && HAVE_DUP2
>	dup2(0, in[R]);
>	dup2(1, out[W]);
># else
>       .
>       .
>       .
>Larry McVoy 	        mcvoy at rsch.wisc.edu, 
>      		        {seismo, topaz, harvard, ihnp4, etc}!uwvax!mcvoy
>
>"They're coming soon!  Quad-stated guru-gates!"

I usually don't respond to this kind of note; not that the question is
silly, it's just that I feel sure that fifty garzillion other people
will respond anyway.  But I'm bored.

Larry's solution is OK, but I would fix two things.  First, the
arguments to the dup2() calls are backwards:

	dup2(in[R], 0);   /* Duplicate input pipe to standard input */
	dup2(out[W], 1);  /* Duplicate output pipe to standard output */

We want the results to be fd's 0 & 1, so these must be the "newd" arguments.
Also, I would close the pipes afterward; no point keeping them open.

It is important for the parent to close the unused ends of the pipes for
a reason other than tidiness.  If the child dies, the parent may want
to know.  The system (BSD, at least) will send a SIGPIPE to the parent
if the child dies but the parent is still writing to the pipe AND the
child's copy of the descriptor is the only reader.  If the parent's copy
of the read end is still open, the system will not deliver SIGPIPE.

Remember also that the pipes are file descriptors suitable for use with
read() and write().  If you want stream I/O, you'll have to use fdopen()
or something.  This is not important for the child; the stream package 
will start things up after the exec().  

--
****                                                         ****
**** At Digital Lynx, we're almost in Garland, but not quite ****
****                                                         ****

Mike McNally                                    Digital Lynx Inc.
Software (not hardware) Person                  Dallas  TX  75243
uucp: {texsun,killer,infotel}!pollux!bobkat!m5  (214) 238-7474



More information about the Comp.unix.questions mailing list