How to force a file descriptor to buffer my output

我与影子孤独终老i 提交于 2020-01-16 04:05:48

问题


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.

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.

This is on linux if that matters.


回答1:


How to force a file descriptor to buffer my output

If you're using the POSIX write() (or a variant of it), you can't.

The write() call must behave thus:

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.

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.

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

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



来源:https://stackoverflow.com/questions/51483247/how-to-force-a-file-descriptor-to-buffer-my-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!