简体   繁体   English

除非使用fflush(),否则为什么fprintf不会直接写入文件?

[英]Why fprintf doesn't write directly into the file unless fflush() is used?

I have written a daemon that writes a value in a file. 我编写了一个在文件中写入值的守护程序。 What I have observed is that when I keep writing on a file, there is nothing visible in the file. 我观察到的是,当我继续写文件时,文件中没有可见的东西。 in other hand, If I use fflush() method then the characters are visible in the file. 另一方面,如果我使用fflush()方法,则字符在文件中可见。 Why fflush() makes a difference? 为什么fflush()有所作为?

Because it's buffered . 因为它是缓冲的 That means all writes are stored in a buffer in memory until the buffer is flushed. 这意味着所有写操作都存储在内存中的缓冲区中,直到刷新缓冲区为止。 For printf and friends it's when it has either a newline, or you explicitly call fflush , or of course if the buffer becomes full. 对于printf和朋友来说,它是换行符,或者是显式调用fflush ,或者缓冲区是否已满。

By default, stdio is fully buffered, unless it's writing to a terminal, in which case it's line-buffered, or stderr, which is not buffered at all. 默认情况下,stdio是完全缓冲的,除非它正在写入终端,在这种情况下,它是行缓冲的,或者是stderr,后者根本没有缓冲。

You can disable buffering with the setbuf() function. 您可以使用setbuf()函数禁用缓冲。

setbuf(fp, NULL);

fprintf is an IO routine provided by the libc, it use caching mechanism by default, before doing a real write into files. fprintf是libc提供的IO例程,在实际写入文件之前,默认情况下它使用缓存机制。

Characters are normally accumulated and transmitted asynchronously to the file in a block, so the cache must exceed the libc(stdio) internal buffer size (BUFSIZE, #defined in stdio.h) or when a fflush() has occurred. 通常,字符是在块中累积并异步传输到文件的,因此缓存必须超过libc(stdio)内部缓冲区大小(BUFSIZE,在stdio.h中定义为#)或发生fflush()时。

If you want to minimize the caching i suggest you to use O_DIRECT or O_SYNC flags for your open call, but there is some restrictions: you must ensure alignment of your buffers and other stuffs. 如果要最大程度地减少缓存,我建议您对open调用使用O_DIRECT或O_SYNC标志,但是有一些限制:必须确保缓冲区和其他填充物对齐。 Read the O_DIRECT section of man 2 open . 阅读man 2 openO_DIRECT 部分

you may also read this for further informations on how to control libc buffering. 您也可以阅读此内容,以获取有关如何控制libc缓冲的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM