Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 7 down vote accepted

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

share|improve this answer
1  
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. –  Random832 Mar 16 '13 at 21:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.