如果我在 "sync" 之前关闭设备会怎样?

what happens if I turn off a device before "sync"?

我有一个嵌入式设备 (Linux + BusyBox),我在其中加载了一个文件 "my_file.txt"。我用 cat 检查文件的内容,结果令人满意。然后,我拔下插头,重启后,我看到文件还在,但大小为 0 字节...

这可能是由不同步的文件系统引起的吗?这实际上是一个双面问题:

  1. 文件的创建和内容的复制是否发生在不同的阶段? (允许一个阶段存在一个 0 字节的文件)
  2. 有没有可能我 "see" 文件 [意思是我成功地 cat "my_file.txt"],但我实际看到的是缓存版本重启后不会出现,除非调用 sync和 "not be there" 我的意思是内容,因为文件本身仍然存在

顺便说一句,Linux 什么时候刷新文件系统?我知道 stdout,例如,在引入 "\n" 时(默认情况下)被刷新 [并且可以以某种方式配置,不记得具体如何]。文件系统也有规则吗?

如果您在处理项目中的文件时关闭设备,它可能会破坏您的文件,因为例如您想要擦除文件的文档并再次写入 it.my 如果您的设备在两者之间关闭这两个阶段和你的文件销毁。

Is the createion of a file and the copy of its contens happen in different stages? (allowing a phase where a file with 0 bytes exists)

是的。对文件的正常操作是

  1. open/create 文件
  2. read/write数据。
  3. 关闭文件。

Is it possible that I "see" the file [meaning I successfully managed to cat "my_file.txt"], but what I actually see, is a cached version that will not be there after reboot, unless a sync will be called?

是的。如果上述第 1 步已同步到硬盘,但第 2 步未同步,则文件内容丢失。

BTW, when does Linux flush filesystems? I know that stdout, for example, is flushed (by default) when a "\n" is introduced [and can be configured somehow, don't remember exactly how]. Is there a rule for filesystems as well?

不,没有通用规则 - 这很复杂。 OS/Kernel 和文件系统将数据缓存在 RAM 中,并在其内部算法认为是这样做的好时机时将其写入磁盘。

请注意,flush/sync 在很多层面上。你说的flush"when a "\n"引入",只是从程序到操作系统的flush。然后操作系统可能只将数据保存在 RAM 中,稍后将其刷新到硬盘驱动器。 硬盘驱动器甚至可以将其缓存在硬盘驱动器上的 RAM 中,稍后将其写入永久存储器。

通常您可以在命令行上运行 sync 命令以确保所有缓存数据都从OS 写入硬盘。 (虽然低端硬盘驱动器的板载 RAM 没有电池备份,但如果断电,这仍然可能会丢失驻留在硬盘驱动器板载 ram 中的数据)。

  1. Is the createion of a file and the copy of its contens happen in different stages? (allowing a phase wehre a file with 0 bytes exists)

是的,复制文件不是原子操作,因为您首先调用 open() 然后 write() 之后...以 O_CREAT 模式打开将创建一个空文件,所以是的:首先是一个空文件,然后填充。

  1. Is it possible that I "see" the file [meaning I successfully managed to cat "my_file.txt"], but what I actually see, is a cached version that will not be there after reboot, unless a sync will be called? and by "not be there" I mean the contens, as the file itself remains

没错,你看到的是之前操作的缓存版本。

when does Linux flush filesystems?

一般规则是内核在需要时刷新内容。你唯一能做的就是要求冲洗,但唉,这只是一个询问,并不意味着冲洗发生了,它只是意味着冲洗很快就会发生。对应的命令行为sync.

Is there a rule for filesystems as well?

您可以挂载一个文件系统,请求 IOs 以直接模式创建,或者您可以逐个文件地请求它(参见 O_DIRECTopen).但请注意,直接模式通常会降低性能...