如何强制文件描述符缓冲我的输出 [英] How to force a file descriptor to buffer my output

查看:57
本文介绍了如何强制文件描述符缓冲我的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多人希望关闭其文件描述符上的缓冲.我要相反:我故意要配置一个文件描述符,以便在写入磁盘之前缓冲例如1K的数据.

Lots of people want to switch off buffering on their file descriptors. I want the reverse: I deliberately want to configure a file descriptor to buffer, say, 1K of data before writing to disk.

原因是我正在为C ++类的冲洗"功能编写单元测试.为了测试它是否正常工作,我想写一些数据,检查磁盘上文件的大小,然后刷新,然后检查大小是否增加.但是实际上,在我进行第一个文件大小检查时,数据已经被写入.

The reason is that I'm writing a unit test for a "flush" function of a C++ class. To test that it's working I want to write some data, check the size of the file on disk, then flush, then check that the size has grown. But in practice, by the time I do the first file size check the data has already been written.

请注意,我在这里使用的是原始文件描述符,而不是流或其他任何内容.

Note that I'm working with a raw file descriptor here, not a stream or anything.

这在Linux上很重要.

This is on linux if that matters.

推荐答案

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

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

write()调用必须具有以下行为:

The write() call must behave thus:

对常规文件的 write()成功返回后:

  • 通过该写操作修改的文件中每个字节位置的任何成功 read()都应返回由 write()直到该字节位置再次出现修改.

  • 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.

任何随后成功执行 write()到文件中相同字节位置的操作,都将覆盖该文件数据.

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

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

Those requirements mean the data written is visible to any other process on the system, and to be consistent, if the data written causes the file size to grow, the file size reported by the kernel must reflect the data written.

我想写一些数据,检查磁盘上文件的大小,然后刷新,然后检查大小是否增大.

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()不缓冲数据.

That fundamentally doesn't work with write(). The file size will grow as the data written - write() does not buffer data.

如果要执行此操作,则必须实现自己的文件系统-与POSIX不兼容的文件系统.

If you want it to do that, you'll have to implement your own filesystem - one that isn't POSIX compliant.

这篇关于如何强制文件描述符缓冲我的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆