Considering two functions that flush buffers:
fflush()
sync()
How can I know when a call to either one is needed?
I know adding a '\n'
to printf()
will flush the output buffer, but if the string contains no such character, when can I skip this call, and when not (multi-threaded systems?)?
Same goes for sync
. I have a function that saves files into the file system (the saving is done via a series of system calls), and it seems that without a call to sync
the files are not saved in a specific case
Unfortunately I don't have all of the details on that case currently [What I do know is that the files are saved and a power off occurs right after that (don't know exactly how soon) and the files are not there after reboot]. On all the tests I run, the files were saved correctly.
So, how can I figure out when the system will flush the file data/metadata buffers and when it will not and I'm needed to explicitly call sync()
?
Quoting man (which does not specify when an explicit call is needed):
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.
A side question:
The 1st comment on this answer shows a way to disable stdout
buffering by using setbuf(stdout, NULL);
. Is there something like for sync
(what buffer is used for that?)?