gpt4 book ai didi

c++ - 在数据写入磁盘之前 fwrite 是否会阻塞?

转载 作者:可可西里 更新时间:2023-11-01 09:47:09 32 4
gpt4 key购买 nike

fwrite() 函数是在将要写入磁盘的数据移交给操作系统后返回,还是仅在数据实际物理写入磁盘后才返回?

对于我的情况,我希望这是第一种情况,因为我不想等到所有数据都物理写入磁盘。我希望另一个操作系统线程在后台传输它。

我很好奇在这种特殊情况下 Windows 10 上的行为。

https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fwrite

最佳答案

在使用fwrite()时,为了提高效率,有几个地方需要缓冲数据:C++运行时缓冲,操作系统文件系统接口(interface)缓冲,实际缓冲磁盘硬件。

这些的默认设置是延迟将数据实际物理写入磁盘,直到有刷新缓冲区的实际请求,或者在发出写入请求时打开适当的指示器以执行物理写入。

如果您想更改fwrite() 的行为,请查看setbuf() 函数setbuf redirection以及setbuff() Linux man page这是Microsoft documentation on setbuf() .

如果您查看底层 Windows CreateFile() function 的文档您会看到有许多标志,其中包括关于是否应该进行数据缓冲的标志。

FILE_FLAG_NO_BUFFERING 0x20000000

The file or device is being opened with no system caching for data reads and writes. This flag does not affect hard disk caching or memory mapped files.

There are strict requirements for successfully working with files opened with CreateFile using the FILE_FLAG_NO_BUFFERING flag, for details see File Buffering.

并查看 Microsoft documentation topic File Buffering .

In a simple example, the application would open a file for write access with the FILE_FLAG_NO_BUFFERING flag and then perform a call to the WriteFile function using a data buffer defined within the application. This local buffer is, in these circumstances, effectively the only file buffer that exists for this operation. Because of physical disk layout, file system storage layout, and system-level file pointer position tracking, this write operation will fail unless the locally-defined data buffers meet certain alignment criteria, discussed in the following section.

看看这个关于操作系统级别设置的讨论,看起来像是 Linux https://superuser.com/questions/479379/how-long-can-file-system-writes-be-cached-with-ext4

关于c++ - 在数据写入磁盘之前 fwrite 是否会阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003849/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com