DevNull DevNull - 2 months ago 8
C Question

read() from pipe guaranteed to provide all atomically written data before EOF?

I'm using a simple

fork()
parent-child example to have the child generate some data, and
write()
it for the parent. The child will atomically write less than
64kib
(65536 bytes) of data atomically to the pipe.

The parent reads from the pipe, and when it receives
EOF
(ie: assuming that the remote side has been closed), it carries on with some processing logic and closes at its own convenience, and doesn't care how long it takes the child to terminate.

Is the parent guaranteed to be able to read all of the client data that was sent before
EOF
is encountered, or does any potential OS-level logic kick in to trigger the
EOF
early before all of the data is read?

I have found a very similar question on SO, but it didn't receive an authoritative/cited answer.

Thank you.

Answer

Yes, the parent will be able to read all the data. To put your mind at ease, try the following in a shell:

echo test | (sleep 1; cat)

The echo command is done immediately; the other side of the pipe will wait one second and then tries to read from it. This just works.

The child can also write more than 64 kiB without problems, as long as the parent will keep on reading in a loop, although then it won't be atomic any longer.

Comments