41

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?

1 Answer 1

41

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)).

9
  • 7
    PIPE_BUF is, by the way, guaranteed to be at least 512. Note that you also have to guarantee that your process actually writes each line to it in a single write call. Enabling line buffering (setvbuf(stdout, NULL, _IOLBF,512)) will do this without requiring you to use low-level functions. Commented Mar 16, 2013 at 21:41
  • 1
    @AlexanderMills: I don't understand your comment Commented Apr 20, 2018 at 11:34
  • 2
    @AlexanderMills: no, that's the minimum value Commented Apr 21, 2018 at 5:45
  • 2
    The spec says that up to PIPE_BUF bytes can be written atomically and will not be interleaved with any other writer. And PIPE_BUF is guaranteed to be a number that is 512 or more. Commented Oct 1, 2020 at 9:03
  • 1
    What about READ? when a process reads, the whole content is read and if other process tries to read while the other is reading, the reading will be blocked for the second process? Commented Mar 17, 2021 at 17:56

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.