Is it possible for read
to
- block
- return less data than requested
when reading from a regular file, excluding:
- request more data than SSIZE_MAX
- reading beyond EOF
- signal interupt
read(3)
suggests that, excluding the above conditions, when reading from a regular file read
will never return fewer bytes than requested.
The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading.
However, this answer suggests a hypothetical in which read
may return fewer bytes than requested if the kernel wishes to prioritize other I/O. While a hypothetical, the point is that under no conditions can read be expected return exactly as much data as requested. So it is never safe, even if the above three conditions (SSIZE_MAX, EOF, interrupt) do not apply, to use read
on a regular file without checking the return value:
// all blockable signals have been ignored
// 10 is guaranteed less than SSIZE_MAX
// file size is known, access is locked
if (read(fd_of_big_reg_file_with_zero_offset, buf, 10) < 0) {
// so all we have to do is handle errors
}
Furthermore, I have never experienced a read on a regular file to block, but I assume it is possible in the event of a recoverable I/O error, such as a bad block requiring multiple rereads.