Traditional UNIX has a buffer cache or page cache in the kernel, and most disk I/O is buffered. When writing data to a file, the kernel usually copies the data into one of the buffers, and if the buffer is not yet full, it is not queued to the output queue, but waits for it to be full, or when the kernel needs to reuse the buffer to hold other disk block data, then the buffer is queued to the output queue, and then when it arrives at the first To perform the actual I/O operation. This output mode is a deferred write (delayed write).
Deferred write reduces the number of disk reads and writes, but reduces the speed of file content updates. In the event of a system failure, this delay may result in the loss of file update content. To ensure consistency between the actual file system on the disk and the content in the buffer cache, the UNIX system provides sync, Fsync, and Fdatasync three functions.
#include <unistd.h>void sync (void); int fsync (int filedes); int fdatasync (int filedes);
Return value: Returns 0 if successful, 1 for error
The sync function Simply queues all the modified block buffers into the write queue and then returns, not waiting for the actual write disk operation to end.
The system daemon, often called update, calls the Sync function periodically (typically every 30 seconds). A block buffer is guaranteed to flush the kernel periodically. Command Sync also calls the sync function.
The Fsync function works only on a single file specified by the file descriptor Filedes, and waits for the write disk operation to end and then returns.
The Fdatasync function is similar to Fsync, but it affects only the data portion of the file.
Sync/fsync function