c - 'file data' 和 'file size' 是一起还是单独提交到磁盘

标签 c file-io synchronization filesize robustness

考虑这个例子:

FILE* stream = fopen("my_file", "w");
fputs("hello", stream);

如果在执行 fputs() 期间断电会发生什么情况?

之后,我能否找到非零大小但第一个字节不是“h”的“my_file”? 如果是,它是否保证为零,还是可以包含任意值?

当然,假设没有其他人接触我们的文件。

编辑:还假设目标磁盘驱动器/设备的类型能够保持足够长的电力来写入它在内部缓冲的所有数据。

POSIX 对此有什么要说的吗?有Linux吗? Windows 有吗?

编辑:我无意关注如何实现 STDIO 流 API 的细节。假设 POSIX,这就是我真正的意思:

int fd = open("my_file", O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
write(fd, "hello", 5);

编辑:POSIX 将文件的大小视为文件的元数据,因此问题可能可以改写为:作为代码的结果,文件数据和该文件的元数据是否可以在不同的阶段提交到磁盘以上?

编辑:在 http://www.sqlite.org/atomiccommit.html 中找到这个:

7.5 Filesystems With Safe Append Semantics

Another optimization introduced in SQLite version 3.5.0 makes use of "safe append" behavior of the underlying disk. Recall that SQLite assumes that when data is appended to a file (specifically to the rollback journal) that the size of the file is increased first and that the content is written second. So if power is lost after the file size is increased but before the content is written, the file is left containing invalid "garbage" data. The xDeviceCharacteristics method of the VFS might, however, indicate that the filesystem implements "safe append" semantics. This means that the content is written before the file size is increased so that it is impossible for garbage to be introduced into the rollback journal by a power loss or system crash.

这似乎至少提供了部分答案。

最佳答案

关于linux,您写入缓冲区的内容不能保证立即写入磁盘。

内核数据复制到缓冲区中,稍后在后台,内核收集所有脏缓冲区,对它们进行最佳排序并将它们写出到磁盘。这称为writeback。这允许写入调用以闪电般的速度发生,几乎立即返回。它还允许内核将延迟写入到更多空闲期并将许多写入批处理。

关于c - 'file data' 和 'file size' 是一起还是单独提交到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14443431/

相关文章:

c - 有C语言的解释器吗?

windows - teracopy 如何替换默认的 Windows 副本

python - Python 何时将文件写入磁盘?

java - 同步线程执行顺序的变化

java - 为什么ArrayList、HashMap等类没有同步?

c - 数组大小错误

java - c 的远程方法调用

c - 参数类型不兼容和类型冲突

c# - 将数据写入文本文件

java - 同步(this)和同步(其他对象)之间有什么区别