The Linux Programming Interface

(nextflipdebug5) #1

918 Chapter 44


The impact of the O_NONBLOCK flag when writing to a pipe or FIFO is made complex
by interactions with the PIPE_BUF limit. The write() behavior is summarized in
Table 44-3.

The O_NONBLOCK flag causes a write() on a pipe or FIFO to fail (with the error EAGAIN)
in any case where data can’t be transferred immediately. This means that if we are
writing up to PIPE_BUF bytes, then the write() will fail if there is not sufficient space in
the pipe or FIFO, because the kernel can’t complete the operation immediately
and can’t perform a partial write, since that would break the requirement that
writes of up to PIPE_BUF bytes are atomic.
When writing more than PIPE_BUF bytes at a time, a write is not required to be
atomic. For this reason, write() transfers as many bytes as possible (a partial write)
to fill up the pipe or FIFO. In this case, the return value from write() is the number
of bytes actually transferred, and the caller must retry later in order to write the
remaining bytes. However, if the pipe or FIFO is full, so that not even one byte can
be transferred, then write() fails with the error EAGAIN.

44.11 Summary


Pipes were the first method of IPC under the UNIX system, and they are used fre-
quently by the shell, as well as in other applications. A pipe is a unidirectional, limited-
capacity byte stream that can be used for communication between related processes.
Although blocks of data of any size can be written to a pipe, only writes that do not
exceed PIPE_BUF bytes are guaranteed to be atomic. As well as being used as a
method of IPC, pipes can also be used for process synchronization.

Table 44-2: Semantics of reading n bytes from a pipe or FIFO containing p bytes

O_NONBLOCK
enabled?

Data bytes available in pipe or FIFO (p)
p = 0, write end open p = 0, write end closed p < n p >= n
No block return 0 (EOF) read p bytes read n bytes
Yes fail (EAGAIN)return 0 (EOF)read p bytes read n bytes

Table 44-3: Semantics of writing n bytes to a pipe or FIFO

O_NONBLOCK
enabled?

Read end open Read end
n <= PIPE_BUF n > PIPE_BUF closed

No

Atomically write n bytes;
may block until sufficient
data is read for write() to
be performed

Write n bytes; may block until
sufficient data read for write() to
complete; data may be interleaved
with writes by other processes
SIGPIPE
+
EPIPE
Yes

If sufficient space is
available to immediately
write n bytes, then write()
succeeds atomically;
otherwise, it fails (EAGAIN)

If there is sufficient space to
immediately write some bytes,
then write between 1 and n bytes
(which may be interleaved with
data written by other processes);
otherwise, write() fails (EAGAIN)
Free download pdf