Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does close() call fsync() on Linux? [duplicate]

Tags:

c

linux

unix

When we call close(<fd>), does it automatically do fsync() to sync to the physical media?

like image 638
user1783732 Avatar asked Mar 11 '13 20:03

user1783732


2 Answers

It does not. Calling close() DOES NOT guarantee that contents are on the disk as the OS may have deferred the writes.

As a side note, always check the return value of close(). It will let you know of any deferred errors up to that point. And if you want to ensure that the contents are on the disk always call fsync() and check its return value as well.

One thing to keep in mind is what the backing store is. There are devices that may do internal write deferring and content can be lost in some cases (although newer storage media devices typically have super capacitors to prevent this, or ways to disable this feature).

like image 196
Jesus Ramos Avatar answered Sep 19 '22 21:09

Jesus Ramos


From man 2 close:

A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a file system to flush the buffers when the stream is closed. If you need to be sure that the data is physically stored use fsync(2). (It will depend on the disk hard-ware at this point.)

To answer your question, NO, close() does not guarantee fsync()

close only closes the file descriptor for the process and removes any record locks associated with the process.

like image 30
Tuxdude Avatar answered Sep 17 '22 21:09

Tuxdude