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 the data and trans return the number of bytes requested. Otherwise, write() shall transfer no data and return -1 with errno set to [EAGAIN].
這個要自己寫程式碼實現,可以參考資料庫裡的事務的實現方式
如果你的應用場景是A寫文件,B讀的話,擔心A寫到一半B就開始讀的話,可以:
1.A寫完了訊息通知B再去讀。
2.A先寫入一個temp文件,全部寫完後將文件改名為B的目標檔。
如果題主說的是POSIX 裡面的
write()
的話,方法是有的,即保證每次寫入的資料不超過PIPE_BUF
就能做到原子性,詳見write()
的文件中關於原子性和O_NONBLOCK
模式下的邏輯說明。PIPE_BUF
是個宏,linux 的話定義在<linux/limits.h>
,其他平台我不太清楚。