The Linux Programming Interface

(nextflipdebug5) #1

916 Chapter 44


If the other end of the FIFO is already open, then the O_NONBLOCK flag has no effect
on the open() call—it successfully opens the FIFO immediately, as usual. The
O_NONBLOCK flag changes things only if the other end of the FIFO is not yet open, and
the effect depends on whether we are opening the FIFO for reading or writing:

z If the FIFO is being opened for reading, and no process currently has the write
end of the FIFO open, then the open() call succeeds immediately ( just as
though the other end of the FIFO was already open).
z If the FIFO is being opened FIFO for writing, and the other end of the FIFO is
not already open for reading, then open() fails, setting errno to ENXIO.

The asymmetry of the O_NONBLOCK flag depending on whether the FIFO is being
opened for reading or for writing can be explained as follows. It is okay to open a
FIFO for reading when there is no writer at the other end of the FIFO, since any
attempt to read from the FIFO simply returns no data. However, attempting to
write to a FIFO for which there is no reader would result in the generation of the
SIGPIPE signal and an EPIPE error from write().
Table 44-1 summarizes the semantics of opening a FIFO, including the effects
of O_NONBLOCK described above.

Using the O_NONBLOCK flag when opening a FIFO serves two main purposes:

z It allows a single process to open both ends of a FIFO. The process first opens
the FIFO for reading specifying O_NONBLOCK, and then opens the FIFO for writing.
z It prevents deadlocks between processes opening two FIFOs.

A deadlock is a situation where two or more process are blocked because each is
waiting on the other process(es) to complete some action. The two processes
shown in Figure 44-8 are deadlocked. Each process is blocked waiting to open a
FIFO for reading. This blocking would not happen if each process could perform
its second step (opening the other FIFO for writing). This particular deadlock
problem could be solved by reversing the order of steps 1 and 2 in process Y, while
leaving the order in process X unchanged, or vice versa. However, such an arrange-
ment of steps may not be easy to achieve in some applications. Instead, we can
resolve the problem by having either process, or both, specify the O_NONBLOCK flag
when opening the FIFOs for reading.

Table 44-1: Semantics of open() for a FIFO

Type of open() Result of open()
open for additional flags other end of FIFO open other end of FIFO closed

reading

none (blocking) succeeds immediately blocks
O_NONBLOCK succeeds immediately succeeds immediately

writing

none (blocking) succeeds immediately blocks
O_NONBLOCK succeeds immediately fails (ENXIO)
Free download pdf