I understand the working of write()
call wherein it writes the data only to kernel's buffers which is later written to disk by kernel after sorting the data optimally.
Calling fsync()
on file descriptor makes sure that data is written to disk as soon as it's posted in the kernel's buffer.
My question is, whether fsync()
should be called before write() or after write() call. I've read couple of books on the topic, looked on the internal as well but couldn't find a satisfactory answer.
fsync should be called after the write system call. It flushes the file data buffers and the metadata to the physical device.
Alternatively, you can use the O_SYNC flag in the open system call for the file and get the same result for each subsequent write call.