dup()'ed pipe()'s to stdio

Daniel E. Platt platt at ndla.UUCP
Sat Feb 3 11:43:37 AEST 1990


Greetings!

I have a question about what happens to the buffering of stdio
when stdio is re-directed via a dup() from a pipe()'ed file
descriptor before exec'ing.

for example, I've done the following:

	int	fd1[2], 	/* child read, parent write */
		fd2[2];		/* child write, parent read */

	/* ... */

	pipe(fd1);
	pipe(fd2);
	if(fork() == 0){

		close(fd1[1]);	/* close superfluous end */
		close(0);	/* close stdin */
		dup(fd1[0]);	/* redirect stdin to come from df1[0] */
		close(fd2[0]);	/* close superfluous end */
		close(1);	/* close stdout */
		dup(fd2[1]);	/* redirect stdout to go to df2[1] */
		execvp(*av, av);/* av is declared char **av; elsewhere */
	}

	close(fd1[0]);
	close(fd2[1]);

	/* ... */

The result of all of this is that the program in *av will be executed
with fd1[0] directed to the output of *av, and fd2[1] will write to
stdin of *av.  But the question is what happens in the child.

In the child, if I have something like:

	/* ... */

	while(scanf("%d", &i) == 1)
		printf("%d", i * i);

	/* ... */

without first calling:
	
	setbuf(stdin, NULL);
	setbuf(stdout, NULL);

what happens is the parent hangs.  It would appear that the child won't
write its buffer until it fills it up... just like it was writing to
a disk.  However, with the setbuf()'s present, there is no hangup.  I assume
that it knows to create the buffer when it determines that it has been
re-directed.  However, doesn't it know that it was redirected from
a pipe as opposed to being re-directed to or from a disk file?  If I'm
trying to do this to a program for which I only have the binary, and which
uses stdio buffered, is there a way to fool it into not using a buffer?

Thanks in advance! :-)

Dan Platt



More information about the Comp.lang.c mailing list