Red Hat Training

A Red Hat training course is available for Red Hat Enterprise Linux

A.3. fsync

Fsync 称为 I/O 昂贵的操作,但这并不完全正确。
每次点击链接时,Firefox 用于调用 sqlite 库,以转至新页面。名为 fsync 的 SQLite 和因为文件系统设置(主要是 ext3 带有数据排序模式)的 SQLite,在没有发生任何发生时会有一个较长的延迟。如果另一个进程同时复制大型文件,则可能需要很长时间(最多 30 秒)。
然而,在其它情况下,如果 fsync 没有被全部使用,交换机会出现到 ext4 文件系统的问题。Ext3 设置为数据排序模式,每几秒钟刷新内存并将其保存到磁盘中。但是,在使用 ext4 和 laptop_mode 时,保存的间隔较长,数据可能会在系统意外关闭时丢失。现在 ext4 被修补,但我们仍然必须仔细考虑应用程序的设计,并根据情况使用 fsync
以下简单示例显示了如何备份文件或如何丢失数据:
/* open and read configuration file e.g. ./myconfig */
fd = open("./myconfig", O_RDONLY);
read(fd, myconfig_buf, sizeof(myconfig_buf));
close(fd);
...
fd = open("./myconfig", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
write(fd, myconfig_buf, sizeof(myconfig_buf));
close(fd);
更好的方法是:
/* open and read configuration file e.g. ./myconfig */
fd = open("./myconfig", O_RDONLY);
read(fd, myconfig_buf, sizeof(myconfig_buf));
close(fd);
...
fd = open("./myconfig.suffix", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR
write(fd, myconfig_buf, sizeof(myconfig_buf));
fsync(fd); /* paranoia - optional */
...
close(fd);
rename("./myconfig", "./myconfig~"); /* paranoia - optional */
rename("./myconfig.suffix", "./myconfig");