search

Home  >  Q&A  >  body text

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

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

大家讲道理大家讲道理2811 days ago821

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 11:54:51

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

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:54:51

    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.

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:54:51

    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.

    reply
    0
  • Cancelreply