Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

86 File I/O Chapter 3


If we add the line
set_fl(STDOUT_FILENO, O_SYNC);

to the beginning of the program shown in Figure3.5, we’ll turn on the synchronous-
write flag. This causes eachwriteto wait for the data to be written to disk before
returning. Normally in the UNIX System, awriteonly queues the data for writing; the
actual disk write operation can take place sometime later.Adatabase system is a likely
candidate for usingO_SYNC, so that it knows on return from awritethat the data is
actually on the disk, in case of an abnormal system failure.
We expect theO_SYNC flag to increase the system and clock times when the
program runs. Totest this, we can run the program in Figure3.5, copying 492.6 MB of
data from one file on disk to another and comparethis with a version that does the
same thing with theO_SYNCflag set. The results from a Linux system using theext4
file system areshown in Figure3.13.

User CPU System CPU Clock time
Operation (seconds) (seconds) (seconds)

read time from Figure3.6 forBUFFSIZE=4,096 0.03 0.58 8.62
normalwriteto disk file 0.00 1.05 9.70
writeto disk file withO_SYNCset 0.02 1.09 10.28
writeto disk followed byfdatasync 0.02 1.14 17.93
writeto disk followed byfsync 0.00 1.19 18.17
writeto disk withO_SYNCset followed byfsync 0.02 1.15 17.88

Figure 3.13Linuxext4timing results using various synchronization mechanisms

The six rows in Figure3.13 wereall measured with aBUFFSIZEof 4,096 bytes. The
results in Figure3.6 weremeasured while reading a disk file and writing to
/dev/null, so therewas no disk output. The second row in Figure3.13 corresponds to
reading a disk file and writing to another disk file. This is why the first and second
rows in Figure3.13 aredifferent. The system time increases when we write to a disk
file, because the kernel now copies the data from our process and queues the data for
writing by the disk driver.Weexpect the clock time to increase as well when we write
to a disk file.
When we enable synchronous writes, the system and clock times should increase
significantly.Asthe thirdrow shows, the system time for writing synchronously is not
much moreexpensive than when we used delayed writes. This implies that the Linux
operating system is doing the same amount of work for delayed and synchronous
writes (which is unlikely), or else theO_SYNCflag isn’t having the desired effect. In this
case, the Linux operating system isn’t allowing us to set theO_SYNCflag usingfcntl,
instead failing without returning an error (but it would have honored the flag if we
wereable to specify it when the file was opened).
The clock time in the last three rows reflects the extra time needed to wait for all of
the writes to be committed to disk. After writing a file synchronously, we expect that a
call tofsyncwill have no effect. This case is supposed to be represented by the last
Free download pdf