I/O in Linux is done to the Virtual File System (VFS). The VFS caches data structures from the various types of filesystem
(ext?/XFS/BTFS, NFS, COW, FUSE etc). This means that any process I/O can use a common interface. Having the filesystem
structure in memory also makes directory and inode lookups far faster than going to disk each time. Reads may still be
held up whilst the data is retrieved, but writes will simply move the data into buffers, update the VFS and return.¹
A buffer which contains modified data is called a "dirty" buffer and is written out to disk by the system at a time of
its choosing. "Clean" buffers contain a cache of information that is identical to the on-disk copy, so they can be
deleted at any time.
Using sync
forces the system to write out the dirty buffers, and not return until they mave been safely moved off the
system. As "dr_" mentions, this must be done prior to a dismount. Once a dirty buffer has been written out, it remains
in the memory as a clean buffer until such time as the system needs more memory for another purpose.
There is one point to bear in mind however; any external cache is unknown to the system and so sync
may not be totally
safe. NFS is a case in point, once the data has been transmitted to the remote system then the local machine will release
the buffers. The remote machine may not have yet written the data to disk, so needs to be handled seperately. Another
case is the use of external RAID controllers. Again sync
will ensure the data has reached the RAID controller, but
cannot know that the RAID controller has actually written it to disk.
The short answer is that on modern systems you don't normally need to use sync
. However, if you have reason to believe
that some part of the filesystem may become unavailable, then sync
ing is a wise precaution. For example, prior to doing
any changes with LVM it is good practice to sync
just in case there is a failure. Likewise, a sync
prior to adjusting
the network is advisable (if you have NFS or similar), as it would be before moving a system or doing any work on the power.
¹Unless the file was opened with O_SYNC or similar.
sync
. Just tell the system you are going to remove the drive (unmount) and it will sync for you.