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