參考 POSIX 針對 rename() 函數的定義
if a power-cut happens during the re-naming, the original file will be intact because the re-name operation is atomic
因此針對斷電後可能的檔案錯誤,有個處理通則,如下:
- make a copy of the file;
- change the copy;
- synchronize the copy (fsync() or fdatasync())
- re-name the copy to the file (using the rename() libc function or the mv utility).
以我手邊的 TI DM368平台做測試,當加上上述的錯誤處理( fsync + rename) 之後,處理一個1300bytes的檔案,相較原本處理時間約需增加 2ms。
Reference:
- http://www.linux-mtd.infradead.org/faq/ubifs.html#L_atomic_change
- http://pubs.opengroup.org/onlinepubs/009695399/functions/rename.html