Does Linux guarantee the contents of a file is flushed to disc after close()?

When a file is closed using close() or fclose() (for example), does Linux guarantee that the file is written back to (persistent) disc?

What I mean is, if close() returns 0 and then immediately afterwards the power fails, are previously written data guaranteed to persist, i.e. be durable?

The fsync() system call does provide this guarantee. Is closing a file also sufficient?

I can't find anything which makes any claim one way or another at the moment.


Question 2:

If close() does implicitly do an fsync(), is there a way of telling it not to?


Solution 1:

From "man 2 close":

A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes.

The man page says that if you want to be sure that your data are on disk, you have to use fsync() yourself.

Solution 2:

No, close does not perform an fsync(2) and would batter many machines to death if it did so. Many intermediate files are opened and closed by their creator, then opened and closed by their consumer, then deleted, and this very common sequence would require touching the disk if close(2) performed an automatic fsync(2). Instead, the disk is usually not touched and the disk never knows the file was there.

Solution 3:

It is also important to note that fsync does not guarantee a file is on disk; it just guarantees that the OS has asked the filesystem to flush changes to the disk. The filesystem does not have to write anything to disk

from man 3 fsync

If _POSIX_SYNCHRONIZED_IO is not defined, the wording relies heavily on the conformance document to tell the user what can be expected from the system. It is explicitly intended that a null implementation is permitted.

Luckily, all of the common filesystems for Linux do in fact write the changes to disk; unluckily that still doesn't guarantee the file is on the disk. Many hard drives come with write buffering turned on (and therefore have their own buffers that fsync does not flush). And some drives/raid controllers even lie to you about having flushed their buffers.