Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

under what conditions are pipe reads atomic?

Tags:

c

posix

atomic

pipe

man pipe -s7 documents writing to the pipe very well. The part important to me being that the write will only ever be partially completed if O_NONBLOCK is set, and write length is greater than PIPE_BUF.

However, nothing is said about the read end.

I am sending structures representing events through my pipe in blocking mode at the write end. At the read end, i am processing those events (and other things) in an update loop in non-blocking mode.

Since my struct is smaller than PIPE_BUF, will read ALWAYS read a whole number of structs? Or do i need to handle the possibility of only part my struct being read ?

Common sense tells me that read behavior will mirror the documented write behavior, but i would be happier if this was specified.

I'm working on Linux ( kernel 3.8, x86_64 ). But it is important that my code is portable across different UNIX flavors, and CPU architectures.

Thanks. Chris.

like image 596
user2035147 Avatar asked Feb 02 '13 12:02

user2035147


2 Answers

The comments are right: read is not atomic. The whole point of atomicity of write is to allow multiple writers without corruption from interleaving data. Multiple readers are much less useful, but even if they were useful, supporting atomic reads would require maintaining packet boundaries in pipes, which do not exist.

like image 155
R.. GitHub STOP HELPING ICE Avatar answered Oct 23 '22 18:10

R.. GitHub STOP HELPING ICE


Reads from a pipe are not atomic.

From the standard page for read()

The standard developers considered adding atomicity requirements to a pipe or FIFO, but recognized that due to the nature of pipes and FIFOs there could be no guarantee of atomicity of reads of {PIPE_BUF} or any other size that would be an aid to applications portability.

like image 34
novelistparty Avatar answered Oct 23 '22 18:10

novelistparty