"is c read() thread safe?" Code Answer

4

read itself is thread-safe, but that doesn't necessarily mean the things you want to do with it are thread-safe. per posix (2.9.7 thread interactions with regular file operations):

all of the following functions shall be atomic with respect to each other in the effects specified in posix.1-2008 when they operate on regular files or symbolic links:

...

(read is in the list that follows.)

among other things, this means that reading the data and advancing the current file position are atomic with respect to each other, and each byte that's read will be read exactly once. however, there are other considerations that can complicate things for you, especially:

  • short reads: read(fd, buf, n) need not read n bytes. it could read anywhere between 1 and n bytes, and when you call it again to read the remainder, that second read is no longer atomic with respect to the first one.

  • other file types: posix only guarantees atomicity of read for regular files and perhaps a few other types. specific systems like linux probably have stronger guarantees, but i would be cautious.

it may be preferable to use the pread function (where you can specify a file offset to read from without having to seek to that position, and where the resulting file position remains unchanged) or perform locking around your file accesses to avoid such problems.

By j3lamp on February 22 2022

Answers related to “is c read() thread safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.