When we call close(<fd>)
, does it automatically do fsync()
to sync to the physical media?
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).
fsync()
forces the writes to storage, under what conditions would fsync not guarantee contents on the disk (except odd failures and hardware deferred writes which can't be controlled in some cases)? –
Coronal fsync()
cannot guarantee your data has made it to the the actual hardware. The man page for close()
does mention this. –
Aha fsync
, by definition, commits data to stable storage. If it does not, then your system is not POSIX-compliant (i.e., buggy). Yes there are many buggy systems in the world, and yes many of them run Linux, but that does not invalidate this answer, which is perfectly correct. –
Danuloff No.
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 hardware at this point.)
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.
© 2022 - 2024 — McMap. All rights reserved.
fsync()
doesn't either, for the same reasons (the hardware might have deferred the writes). – Aha