如何强制文件描述符缓冲我的输出

How to force a file descriptor to buffer my output

很多人想关闭他们文件描述符的缓冲。我想要相反的情况:我故意要配置一个文件描述符来缓冲,比如说,在写入磁盘之前 1K 的数据。

原因是我正在为 C++ class 的 "flush" 函数编写单元测试。为了测试它是否正常工作,我想写一些数据,检查磁盘上文件的大小,然后刷新,然后检查大小是否增加了。但实际上,当我第一次检查文件大小时,数据已经写入。

请注意,我在这里使用的是原始文件描述符,而不是流或任何东西。

如果重要的话,这是 linux。

How to force a file descriptor to buffer my output

如果您使用的是 the POSIX write()(或其变体),则不能

write() 调用必须如此:

After a write() to a regular file has successfully returned:

  • Any successful read() from each byte position in the file that was modified by that write shall return the data specified by the write() for that position until such byte positions are again modified.

  • Any subsequent successful write() to the same byte position in the file shall overwrite that file data.

这些要求意味着写入的数据对系统上的任何其他进程可见,并且为了保持一致,如果写入的数据导致文件大小增加,则文件大小内核报告的必须反映写入的数据。

I want to write some data, check the size of the file on disk, then flush, then check that the size has grown.

从根本上说 write() 不起作用 。文件大小将随着写入的数据而增长 - write() 不缓冲数据。

如果你想让它这样做,你必须实现你自己的文件系统——一个不 POSIX 兼容的文件系统。