read 'foo'
write 'foo~'
hardlink 'foo~' onto 'foo'
unlink 'foo~'
on crash:
if 'foo' exists:
it's the correct state for the file
unlink 'foo~'
continue
otherwise:
hardlink 'foo~' onto 'foo'
unlink 'foo~'
I'm not sure Posix actually requires link and unlink to be atomic enough on crash for this work, but it seems to be fine for any sane filesystem (where the fs itself doesn't fall apart in presence of crashes).You use a hardlink only for atomic creation of the initial data:
write 'foo~'
hardlink 'foo~' onto 'foo'
To atomically update you simply use rename: read 'foo'
write 'foo~'
rename 'foo~' into 'foo'
I don't know what dan-robertson's claim is based on, but this surely is atomic even on a crash, as the filesystem will never be in a state where 'foo' contains only partially updated data. That would require some severe fs corruption.So in case of a system crash you might end up seeing partial data in 'foo'.
fsync() may or may not protect against that depending on what system we're talking about.
The point of rename() is to prevent a version to ever exist that mixes the old and the new version, which it always does, regardless of the filesystem.
The workflows this would be enable is that, when vim wants syntax checking, it writes a transient version of the file to the fs without updating the “HEAD” pointer and then hands a fd to the syntax checker that points to that new transient version.
Surely, if I do "write foo~", "rename foo~ foo", regardless of any crash, foo is either pointing to the old data or the new data. There simply isn't any inode with any "partially renamed state" mixing the two.