我一直在关注EXT4上的"bug",如果使用"创建临时文件,写入临时文件,将temp重命名为目标文件"进程,会导致文件在崩溃时归零.POSIX说,除非调用fsync(),否则您无法确定数据是否已刷新到硬盘.
显然这样做:
0) get the file contents (read it or make it somehow)
1) open original file and truncate it
2) write new contents
3) close file
Run Code Online (Sandbox Code Playgroud)
即使使用fsync()也不好,因为计算机可能会在2)或fsync()期间崩溃,并且您最终会得到部分写入的文件.
通常认为这是非常安全的:
0) get the file contents (read it or make it somehow)
1) open temp file
2) write contents to temp file
3) close temp file
4) rename temp file to original file
Run Code Online (Sandbox Code Playgroud)
不幸的是它不是.为了使其在EXT4上安全,您需要执行以下操作:
0) get the file contents (read it or make it somehow)
1) open temp file
2) write contents …Run Code Online (Sandbox Code Playgroud)