Can posix read () get less than 4 bytes requested from the pipe?

The program from the answer https://stackoverflow.com/a/2906169/ uses the read () system call to get exactly 4 bytes from the channel. The read () function is supposed to return -1, 0, or 4. Can the read () function return 1, 2, or 3, for example, if it was interrupted by a signal?

The man page read (2) has:

Upon successful completion, the number of bytes read is returned (zero indicates the end of the file), and the file position advances by this number. This is not an error if this number is less than the number of bytes requested; this can happen, for example, because fewer bytes are actually available right now (perhaps because we were close to the end of the file or because we are reading from a pipe or from a terminal), or because read () was interrupted by a signal.

Does this mean that the read () function can be interrupted while receiving as little data as 4 bytes? Should the source code of this answer be corrected?

In the tube of the man (7) page is:

POSIX.1-2001 says that write (2) s less than bytes PIPE_BUF should be atomic: the output is written to the channel as a continuous sequence.

but nothing like read ().

+5
source share
1 answer

If the record is atomic, it means that all the content is already in the buffer when reading occurs, so the only way to get an incomplete read is that the kernel thread decides to leave before it finishes - whatever it is.

In general, you can rely on small () s records on pipes on the same system mapping with the same read () s. 4 bytes is undoubtedly much smaller than any buffer, so it will definitely be atomic.

+2
source

All Articles