【发布时间】:2018-10-02 03:55:12
【问题描述】:
考虑两个刷新缓冲区的函数:
fflush()sync()
我如何知道何时需要呼叫其中任何一个?
我知道将'\n' 添加到printf() 将刷新输出缓冲区,但如果字符串不包含这样的字符,我什么时候可以跳过这个调用,什么时候不可以(多线程系统?)?
sync 也是如此。我有一个将文件保存到文件系统中的函数(保存是通过一系列系统调用完成的),似乎没有调用sync 文件在特定情况下不会保存
不幸的是,我目前没有关于该案例的所有详细信息 [我所知道的是文件已保存,然后立即断电(不知道确切的时间) 并且文件在重新启动后不存在]。在我运行的所有测试中,文件均已正确保存。
那么,我怎么知道系统什么时候会刷新文件数据/元数据缓冲区,什么时候不会,我需要显式调用sync()?
引用 man (未指定何时需要显式调用):
sync, syncfs - commit buffer cache to disk
sync() causes all buffered modifications to file metadata and data to be written to the underlying file systems.
fflush - flush a stream
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application. The open status of the stream is unaffected.
附带问题:
The 1st comment on this answer 展示了一种使用setbuf(stdout, NULL); 禁用stdout 缓冲的方法。 sync 有类似的东西吗(使用什么缓冲区?)?
【问题讨论】:
-
"将 '\n' 添加到 printf() 将刷新输出缓冲区" --> 通常 - 也许:What are the rules of automatic flushing stdout buffer in C?。然而,对于 Linux,它可能是这样指定的。
-
我认为这个问题没有一般的答案。刷新和同步只是 C 库提供的功能。当您详细说明程序的算法时,您将知道何时使用它。
-
CIsForCookies 你有我的 UV,但是当它刷新时需要 1)就在用户输入之前 2)就在打印错误消息之前,3)无论何时。跨度>