ptg10805159
936 Solutions to Selected Exercises Appendix C
Then usefdopento associate the pipe descriptors with a standardI/O stream,
and set the streams to be line buffered. Do this beforethewhileloop that reads
from standardinput:
if ((fpin = fdopen(fd2[0], "r")) == NULL)
err_sys("fdopen error");
if ((fpout = fdopen(fd1[1], "w")) == NULL)
err_sys("fdopen error");
if (setvbuf(fpin, NULL, _IOLBF, 0) < 0)
err_sys("setvbuf error");
if (setvbuf(fpout, NULL, _IOLBF, 0) < 0)
err_sys("setvbuf error");
Thewriteandreadin thewhileloop arereplaced with
if (fputs(line, fpout) == EOF)
err_sys("fputs error to pipe");
if (fgets(line, MAXLINE, fpin) == NULL) {
err_msg("child closed pipe");
break;
}
15.6 Thesystemfunction callswait,and the first child to terminate is the child
generated bypopen.Since that’s not the child thatsystemcreated, it callswait
again and blocks until thesleepis done. Thensystemreturns. Whenpclose
callswait, an error is returned, since thereare nomorechildren towaitfor.
Thenpclosereturns an error.
15.7 Although the details vary by platform (see FigureC.19),selectindicates that
the descriptor is readable. After all the data has been read,readreturns 0 to
indicate the end of file. But withpoll,thePOLLHUPevent is returned, and this
can happen while there is still data to be read. Once we have read all the data,
however,readreturns 0 to indicate the end of file. After all the data has been
read, thePOLLINevent is not returned, even though we need to issue areadto
receive the end-of-file notification (the return value of 0).
FreeBSD Linux Mac OS X Solaris
Operation 8.0 3.2.0 10.6.8 10
selectonreadend of pipe withwriteend closed R/W/E R R/W R/W/E
pollonreadend of pipe withwriteend closed R/HUP HUP INV HUP
selectonwriteend of pipe withreadend closed R/W/E R/W R/W R/W
pollonwriteend of pipe withreadend closed R/HUP W/ERR INV HUP
Figure C.19 Pipe behavior withselectandpoll
The conditions shown in FigureC.19 include R (readable), W (writable), E
(exception), HUP (hangup), ERR (error), and INV (invalid file descriptor). With
an output descriptor that refers to a pipe that has been closed by the reader,
selectindicates that the descriptor is writable. But when we callwrite,the
SIGPIPEsignal is generated. If we either ignorethis signal or return from its