How can rename be atomic when disk sector writes are not?
Solution 1:
The question is: What is meant by the word "atomic", as what you (and most people) will understand is different than what was meant by the author of this phrase.
So let's dispel this myth: "it is atomic so inconsistencies cannot happen". Wrong!
When moving a file inside the same filesystem (rename), the system call is indeed atomic, but what is meant is that this is atomic with respect to the software environment.
Atomicity means here that any process that looks for the file will either see it at its old location or at its new location. No process will be able to observe that the file has a different link count, or that the file is present with the old name/directory after being present in the new name/directory, or that the file is missing under both new and old names.
However, if the system crashes due to a bug, a disk error or a power loss, there is no guarantee that the filesystem is left in a consistent state, let alone that the move isn't left half-done.
Neither Windows nor Linux offer in general a guarantee of
atomicity with respect to hardware events.
Which is why these operating systems include disk test and repair
utilities, chkdsk
for Windows and fsck
in Linux, and many other
utilities both free and commercial.
Some file-system formats offer better resiliency to crashes for the
rename operation. The Linux ext
family may excel here.
More resilient disk file-formats include a journal of operations that
allows to complete or undo interrupted disk operations,
with automatic recovery during the boot.