Linux 中 write 系统调用具有原子性吗?

Linux 中 write 系统调用具有原子性吗?比如两个进程同时 write 同一个文件会不会出现数据交错的情况?

先摆上结论:Linux3.14开始操作普通文件,read(), write()都是原子的以下摘录自manman 2

According to POSIX.1-2008/SUSv4 Section XSI 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: …
Among the APIs subsequently listed are write() and writev(2). And among the effects that should be atomic across threads (and processes) are updates of the file offset. However, on Linux before version 3.14, this was not the case: if two processes that share an open file description (see open(2))
perform a write() (or writev(2)) at the same time, then the I/O operations were not atomic with respect updating the file offset, with the result that
the blocks of data output by the two processes might (incorrectly) overlap. This problem was fixed in Linux 3.14.

虽然write是原子的,但是seek+write不是原子的,为了保证seek+write是原子的,系统提供了O_APPEND标志,当你通过该标识打开一个文件,之后任何追加的写操作都是原子的

参考资料

Linux下多进程写同一文件,要不要加锁?
Linux 中 write 系统调用具有原子性吗?