函数sync、fsync与fdatasync的总结整理(必看篇)

2019-10-13 12:05:35刘景俊

三、总结

1、如果是对所有的缓冲区发出写硬盘的命令,应该使用sync函数,但应该注意该函数仅仅只是把该命令放入队列就返回了,在编程时需要注意。

2、如果是要把一个已经打开的文件所做的修改提交到硬盘,应调用fsync函数,该函数会在数据实际写入硬盘后才返回,因此是最安全最可靠的方式。

3、如果是针对一个已经打开的文件流操作,则应该首先调用fsync函数把修改同步到内核缓冲区,然后再调用fsync把修改真正的同步到硬盘。

四、附man手册关于fsync,fdatasync部分

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 after the sys‐

tem crashed or was rebooted. This includes writing through or flushing a disk cache if present. The call blocks until the device

reports that the transfer has completed. It also flushes metadata information associated with the file (see stat(2)).

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.

fdatasync() is similar to fsync(), but does not flush modified metadata unless that metadata is needed in order to allow a subsequent

data retrieval to be correctly handled. For example, changes to st_atime or st_mtime (respectively, time of last access and time of last

modification; see stat(2)) do not require flushing because they are not necessary for a subsequent data read to be handled correctly. On

the other hand, a change to the file size (st_size, as made by say ftruncate(2)), would require a metadata flush.

The aim of fdatasync() is to reduce disk activity for applications that do not require all metadata to be synchronized with the disk.

Linux、unix在内核中设有缓冲区、高速缓冲或页面高速缓冲,大多数磁盘I/O都通过缓冲进行,采用延迟写技术。

sync:将所有修改过的快缓存区排入写队列,然后返回,并不等待实际写磁盘操作结束;

fsync:只对有文件描述符制定的单一文件起作用,并且等待些磁盘操作结束,然后返回;

fdatasync:类似fsync,但它只影响文件的数据部分。fsync还会同步更新文件的属性;

fflush:标准I/O函数(如:fread,fwrite)会在内存建立缓冲,该函数刷新内存缓冲,将内容写入内核缓冲,要想将其写入磁盘,还需要调用fsync。(先调用fflush后调用fsync,否则不起作用)。

以上就是小编为大家带来的函数sync、fsync与fdatasync的总结整理(必看篇)全部内容了,希望大家多多支持易采站长站~