write文件,是否可以在非阻塞的情况下,保证一次write数据的原子性?

调用write方法的时候,是否有方法可以保证要不就一个字节都不写入,要不就全部都写入?
把场景也描述一下,比如有一个文件有10行记录,读取第5行的记录,进行修改,我希望修改的操作是原子性的,也就是说,read的时候,要不是旧的记录,要不就是新的

阅读 5.2k
3 个回答

这个要自己写代码实现,可以参考数据库里的事务的实现方式

如果你的应用场景是A写文件,B读的话,担心A写到一半B就开始读的话,可以:
1.A写完了消息通知B再去读。
2.A先写入一个temp文件,全部写完后将文件改名为B的目标文件。

如果题主说的是 POSIX 里面的 write() 的话,方法是有的,即保证每次写入的数据不超过 PIPE_BUF 就能做到原子性,详见 write()文档中关于原子性和 O_NONBLOCK 模式下的逻辑说明。

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].

PIPE_BUF 是个宏,linux 的话定义在 <linux/limits.h>,其他平台我不太清楚。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题