c++ - write文件,是否可以在非阻塞的情况下,保证一次write数据的原子性?
大家讲道理
大家讲道理 2017-04-17 11:52:51
0
3
819

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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(3)
洪涛

You need to write your own code to implement this. You can refer to the implementation method of transactions in the database

黄舟

If your application scenario is that A writes a file and B reads it, and you are worried that A will start reading halfway through writing, you can:
1. After A finishes writing the message, he notifies B to read it again.
2.A first writes a temp file, and then renames the file to B's target file after everything is written.

黄舟

If the question is about write() in POSIX, there is a way to achieve atomicity by ensuring that the data written each time does not exceed PIPE_BUF. For details, see the document of write() A note on atomicity and logic in O_NONBLOCK mode.

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 is a macro. For Linux, it is defined in <linux/limits.h>. I am not sure about other platforms.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template