fsync的含义

less than 1 minute read

fsync 是一个系统调用,用于强制将缓冲区中的数据写入磁盘。

在 Linux manual page 的定义是:

synchronize a file’s in-core state with storage device

函数签名是:

 int fsync(int fd);

fd 是文件描述符。返回值是 0 表示成功,-1 表示有错误发生。

具体描述如下:

fsync() transfers (“flushes”) all modified in-core data of (i.e., modified buffer cache pages for) the file referred to by the file descriptor fd to the disk device (or other permanent storage device) so that all changed information can be retrieved even if the system crashes or is rebooted. This includes writing through or flushing a disk cache if present. The call blocks until the device reports that the transfer has completed.

As well as flushing the file data, fsync() also flushes the metadata information associated with the file (see inode(7)).

Calling fsync() does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync() on a file descriptor for the directory is also needed.

可知:

  • 调用 fsync 后,文件才被真正地写入到磁盘等持久化设备中了,这可以保证系统崩溃、机器掉电时文件不丢失或者损坏。 而调用 write 时,只是将数据写到缓冲区中,并不会真正写入到磁盘。

  • 这是一个阻塞的调用。

  • fsync 会更新文件的元数据。

应用场景:fsync的一个常见的应用场景就是数据库程序,它们一般都要保证新增或修改的数据能够立刻持久化到磁盘上。

参考:

Comments