ptg10805159
Section 3.13 sync,fsync,andfdatasyncFunctions 81
- dup2is an atomic operation, whereas the alternate form involves two function
calls. It is possible in the latter case to have a signal catcher called between the
closeand thefcntlthat could modify the file descriptors. (Wedescribe
signals in Chapter 10.) The same problem could occur if a different thread
changes the file descriptors. (Wedescribe threads in Chapter 11.) - Thereare someerrnodifferences betweendup2andfcntl.
Thedup2system call originated with Version 7 and propagated through the BSD releases. The
fcntlmethod for duplicating file descriptors appeared with System III and continued with
System V.SVR3.2 picked up thedup2function, and 4.2BSD picked up thefcntlfunction and
theF_DUPFDfunctionality.POSIX.1 requires bothdup2and theF_DUPFDfeatureoffcntl.
3.13 sync,fsync,and fdatasyncFunctions
Tr aditional implementations of the UNIX System have a buffer cache or page cache in
the kernel through which most disk I/O passes. When we write data to a file, the data
is normally copied by the kernel into one of its buffers and queued for writing to disk at
some later time. This is calleddelayed write.(Chapter 3 of Bach[ 1986 ]discusses this
buffer cache in detail.)
The kernel eventually writes all the delayed-write blocks to disk, normally when it
needs to reuse the buffer for some other disk block. To ensureconsistency of the file
system on disk with the contents of the buffer cache, thesync,fsync,andfdatasync
functions areprovided.
#include <unistd.h>
int fsync(intfd);
int fdatasync(intfd);
Returns: 0 if OK,−1 on error
void sync(void);
Thesyncfunction simply queues all the modified block buffers for writing and returns;
it does not wait for the disk writes to take place.
The functionsyncis normally called periodically (usually every 30 seconds) from a
system daemon, often calledupdate.This guarantees regular flushing of the kernel’s
block buffers. The commandsync( 1 )also calls thesyncfunction.
The functionfsyncrefers only to a single file, specified by the file descriptorfd,
and waits for the disk writes to complete beforereturning. This function is used when
an application, such as a database, needs to be surethat the modified blocks have been
written to the disk.
Thefdatasyncfunction is similar tofsync,but it affects only the data portions of
afile. Withfsync,the file’s attributes arealso updated synchronously.
All four of the platforms described in this book supportsyncandfsync.However,FreeBSD
8.0 does not supportfdatasync.