reading and writing to another process

Dave Sherman dave at utcsrgv.UUCP
Mon Oct 3 14:00:33 AEST 1983


Since pipes are one of the real obscurities of UNIX, and this is
supposedly a group for novices, here's a posted answer to nsc!chongo:

	int pipeline[2];

	pipe(pipeline);	/* check it returns -1 to be safe */

	pid = fork();	/* again, check for -1 */

	if(pid == 0)	/* child */
	{
		close(0);
		dup(pipeline[0]);
		close(pipeline[0]);

		close(1);
		dup(pipeline[1]);
		close(pipeline[1]);

		execl(bar .......)
		/* exit with error message about execl failing */
	}

	/* parent */
	write(pipeline[1], ....) to write on the pipe
	read(pipeline[0], ....) to read from the pipe


Presto. Now the child will write to the pipe when writing to stdout,
and read from the pipe when reading stdin.

The dup works because it uses the lowest available file descriptor.
Since you just closed 0, dup() will dup it to 0. It has the effect
of making reads on the pipeline[0] be reads from 0 too. Obscure indeed.
It takes a little getting used to (so did printf when I first saw it).


Dave Sherman
-- 
 {cornell,decvax,ihnp4,linus,utzoo,uw-beaver}!utcsrgv!lsuc!dave



More information about the Comp.unix mailing list