Atomic/non-atomic: A write is atomic if the whole amount written in one operation is not interleaved with data from any other process. ... This volume of POSIX.1-2008 ... requires that writes of {PIPE_BUF} or fewer bytes shall be atomic.
If the O_NONBLOCK flag is set ... A write request for {PIPE_BUF} or fewer bytes shall have the following effect: if there is sufficient space available in the pipe, write() shall transfer all the data and return the number of bytes requested. Otherwise, write() shall transfer no data and return -1 with errno set to [EAGAIN].
这个要自己写代码实现,可以参考数据库里的事务的实现方式
如果你的应用场景是A写文件,B读的话,担心A写到一半B就开始读的话,可以:
1.A写完了消息通知B再去读。
2.A先写入一个temp文件,全部写完后将文件改名为B的目标文件。
如果题主说的是 POSIX 里面的
write()
的话,方法是有的,即保证每次写入的数据不超过PIPE_BUF
就能做到原子性,详见write()
的文档中关于原子性和O_NONBLOCK
模式下的逻辑说明。PIPE_BUF
是个宏,linux 的话定义在<linux/limits.h>
,其他平台我不太清楚。