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.
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 exceedPIPE_BUF
. For details, see the document ofwrite()
A note on atomicity and logic inO_NONBLOCK
mode.PIPE_BUF
is a macro. For Linux, it is defined in<linux/limits.h>
. I am not sure about other platforms.