I want to use pipes on Linux as a synchronization primitive between a master process and a slave process. The classic way is to create two pipes, but I believe there's a way to use a single fd instead. Consider:
- The slave creates
r
-w
pipe. - Read end
r
is passed to the master. - When the slave is ready, it writes to
w
N bytes, then N bytes again, then 1 byte, where N is the pipe buffer size. The firstwrite(2)
returns immediately, the second blocks because the buffer is full. - Master blocks and reads from
r
. The secondwrite(2)
returns, the thirdwrite(2)
blocks. - After the master has read data, it does whatever stuff it has to.
- When the slave is to be resumed, master reads once more from
r
. The thirdwrite(2)
returns and the slave proceeds.
However, the man page for fcntl
says this:
Changing the capacity of a pipe
F_SETPIPE_SZ (int; since Linux 2.6.35)
...
Note that because of the way the pages of the pipe buffer are
employed when data is written to the pipe, the number of bytes
that can be written may be less than the nominal size, depend‐
ing on the size of the writes.
The man page seems to say that if the pipe buffer size is N bytes and I write M<=N bytes to the pipe, it is possible that the write will block. In what cases can that happen (except the simple case when there is already much data in the pipe)?
Additionally, "depending on the size of the writes" sounds odd. Can I get this strange behavior if I write exactly N bytes?