yohhoyの日記

技術的メモをしていきたい日記

アトミックなファイル更新

POSIX環境またはWindows環境において、ファイルシステム上でアトミック(atomic; 不可分)なファイル更新を実現する方法。

まとめ:

  • POSIX:<stdio.h>標準ヘッダrename関数を利用する。
  • Windowswindows.hヘッダ ReplaceFile 関数が最有力候補。ただし Undocumented な保証にすぎず、データ部のみがアトミック更新との噂。

POSIX

rename関数はアトミック操作であると規定される。POSIX規格(IEEE Std 1003.1-2013 Ed)より一部引用(下線部は強調)。

RATIONALE
This rename() function is equivalent for regular files to that defined by the ISO C standard. Its inclusion here expands that definition to include actions on directories and specifies behavior when the new parameter names a file that already exists. That specification requires that the action of the function be atomic.

http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html

Windows

MSDNには明確な記載がないが、WindowsAPI ReplaceFile関数でアトミックなファイル更新が可能らしい。実際に試した範囲でもアトミック操作だった@Windows 7環境。

同関数への間接的な言及をしているMSDN記事より一部引用(下線部は強調)。*1

Applications updating a single file with "document-like" data
Many applications which deal with "document-like" data tend to load the entire document into memory, operate on it, and then write it back out to save the changes. The needed atomicity here is that the changes either are completely applied or not applied at all, as an inconsistent state would render the file corrupt. A common approach is to write the document to a new file, then replace the original file with the new one. One method to do this is with the ReplaceFile API.

Alternatives to using Transactional NTFS

Microsoft Research発行のTechnical Report (PDF) "To BLOB or Not To BLOB: Large Object Storage in a Database or a Filesystem?" より一部引用。

2.2. Safe writes
(snip) Under UNIX, rename() is guaranteed to atomically overwrite the old version of the file. Under Windows, the ReplaceFile() call is used to atomically replace one file with another.

http://stackoverflow.com/questions/167414/#comment38520206_2368286 より引用。参考程度に。

Microsoft intern here. I had this problem, so I asked a guy who worked on NTFS. The part where data is moved is atomic, so while it can be interrupted while the file attributes are being modified, the part where data itself is moved is atomic. - zneak Jul 17 '14 at 22:13

関連URL

*1:該当記事は非推奨となった Transactional NTFS(TxF) の代替機能について説明したもの。TxF はWindows Vistaで導入されたが、Windows 8以降では非推奨となる。