fork vs. pipe

Pete Zaitcev zaitcev at redhat.com
Sat Feb 26 00:15:30 UTC 2011


Hi, Jeff:

In iwhd's s3_register(), a subprocess is forked and the parent parses
its output. However, for some reason the waitpid is done before the
reading of the pipe starts, like so:

	pipe(organ);
	pid = fork();
	if (pid == 0) {
		(void)dup2(organ[1],STDOUT_FILENO);
		(void)dup2(organ[1],STDERR_FILENO);
		execvp(cmd, (char* const*)argv);
		error (EXIT_FAILURE, errno, "failed to run command %s", cmd);
	}
	waitpid(pid,NULL,0);
	close(organ[1]);
	fp = fdopen(organ[0],"r");
	while (fgets(buf,sizeof(buf)-1,fp)) {
		.....
	}

What is the point of doing it this way? My concern is that a child
that prints too much may overflow pipe's buffers, block, and then
the parent will wait forever inside waitpid().

I thought it was safer to read everything in the parent, without
calling waitpid, until EOF, an only then collect the exit status.
There is no way for a process to exit and not form EOF on a pipe,
is there?

-- Pete


More information about the iwhd-devel mailing list