Linux – Guarantees for Concurrent Writes into a Named Pipe

linuxpipe

For example, I created a named pipe like the following:

mknod myPipe p

And I read from it from some process (for example, some server). For example purposes, I used tail:

tail -f myPipe

If several client processes write some messages into it (for example, echo "msg" >> myPipe, is there some chance that messages will get interleaved, like this:

 <beginning of message1><message2><ending of message1>

Or is the process of writing to named pipe is atomic?

Best Answer

It depends on how much each process is writing (assuming your OS is POSIX-compliant in this regard). From write():

Write requests to a pipe or FIFO shall be handled in the same way as a regular file with the following exceptions:
[...]

  • Write requests of {PIPE_BUF} bytes or less shall not be interleaved with data from other processes doing writes on the same pipe. Writes of greater than {PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with writes by other processes, whether or not the O_NONBLOCK flag of the file status flags is set.

Also in the Rationale section regarding pipes and FIFOs:

  • Atomic/non-atomic: A write is atomic if the whole amount written in one operation is not interleaved with data from any other process. This is useful when there are multiple writers sending data to a single reader. Applications need to know how large a write request can be expected to be performed atomically. This maximum is called {PIPE_BUF}. This volume of POSIX.1-2008 does not say whether write requests for more than {PIPE_BUF} bytes are atomic, but requires that writes of {PIPE_BUF} or fewer bytes shall be atomic.

The value if PIPE_BUF is defined by each implementation, but the minimum is 512 bytes (see limits.h). On Linux, it's 4096 bytes (see pipe(7)).