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

前端 未结 3 406
北海茫月
北海茫月 2020-12-22 08:27

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

3条回答
  •  时光说笑
    2020-12-22 09:02

    fprintf is an IO routine provided by the libc, it use caching mechanism by default, before doing a real write into files.

    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.

    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. Read the O_DIRECT section of man 2 open .

    you may also read this for further informations on how to control libc buffering.

提交回复
热议问题