ptg10805159
552 Interprocess Communication Chapter 15
If we invoke this new coprocess from the program in Figure15.18, it no longer
works. The problem is the default standardI/O buffering. When the program in
Figure15.19 is invoked, the firstfgetson the standardinput causes the standardI/O
library to allocate a buffer and choose the type of buffering. Since the standardinput is
apipe, the standardI/O library defaults to fully buffered. The same thing happens
with the standardoutput. Whileadd2is blocked reading from its standardinput, the
program in Figure15.18 is blocked reading from the pipe.We have a deadlock.
Here, we have control over the coprocess that’s being run. Wecan change the
program in Figure15.19 by adding the following four lines beforethewhileloop:
if (setvbuf(stdin, NULL, _IOLBF, 0) != 0)
err_sys("setvbuf error");
if (setvbuf(stdout, NULL, _IOLBF, 0) != 0)
err_sys("setvbuf error");
These lines causefgetsto return when a line is available and causeprintfto do an
fflushwhen a newline is output (refer to Section 5.4 for the details on standardI/O
buffering). Making these explicit calls tosetvbuffixes the program in Figure15.19.
If we aren’t able to modify the program that we’repiping the output into, other
techniques arerequired. For example, if we use awk( 1 ) as a coprocess from our
program (instead of theadd2program), the following won’t work:
#! /bin/awk -f
{print $1 + $2 }
The reason this won’t work is again the standardI/O buffering. But in this case, we
cannot change the wayawkworks (unless we have the source code for it). We are
unable to modify the executable ofawkin any way to change the way the standardI/O
buffering is handled.
The solution for this general problem is to make the coprocess being invoked (awk
in this case) think that its standardinput and standardoutput areconnected to a
terminal. That causes the standardI/O routines in the coprocess to line buffer these
two I/O streams, similar to what we did with the explicit calls tosetvbufpreviously.
We use pseudo terminals to do this in Chapter 19.
15.5 FIFOs
FIFOs aresometimes called named pipes. Unnamed pipes can be used only between
related processes when a common ancestor has created the pipe.With FIFOs, however,
unrelated processes can exchange data.
We saw in Chapter 4 that a FIFO is a type of file. One of the encodings of the
st_modemember of thestatstructure(Section 4.2) indicates that a file is a FIFO. We
can test for this with theS_ISFIFOmacro.
Creating a FIFO is similar to creating a file. Indeed, thepathnamefor a FIFO exists in
the file system.