I would like to ask a fundamental question about when is it useful to use a system call like fsync. I am beginner and i was always under the impression that write is enough to write to a file, and samples that use write actually write to the file at the end.
So what is the purpose of a system call like fsync?
Just to provide some background i am using Berkeley DB library version 5.1.19 and there is a lot of talk around the cost of fsync() vs just writing. That is the reason i am wondering.
Think of it as a layer of buffering.
If you’re familiar with the standard C calls like
fopenandfprintf, you should already be aware of buffering happening within the C runtime library itself.The way to flush those buffers is with
fflushwhich ensures that the information is handed from the C runtime library to the OS (or surrounding environment).However, just because the OS has it, doesn’t mean it’s on the disk. It could get buffered within the OS as well.
That’s what
fsynctakes care of, ensuring that the stuff in the OS buffers is written physically to the disk.You may typically see this sort of operation in logging libraries:
filenois a function which gives you the underlyingintfile descriptor for a givenFILE*file handle, andfsyncon the descriptor does the final level of flushing.Now that is a relatively expensive operation since the disk write is usually considerably slower than in-memory transfers.