This repository has been archived by the owner on Aug 12, 2024. It is now read-only.
This repository has been archived by the owner on Aug 12, 2024. It is now read-only.
Closed
Description
Currently it's possible for downstream readers to read a partially written file because WriteFile
is not atomic. Ideally an updated file would only change once, and the change would be total, so that you'd either read the old state or the new state, but nothing in between.
One way to implement this is by writing to a temporary file and then renaming the file:
func safeWriteFile(dst string, data []byte) error {
tmp := dst + ".tmp"
defer os.RemoveAll(tmp)
err := ioutil.WriteFile(tmp, data, 0755)
if err != nil {
return err
}
return os.Rename(tmp, dst)
}
This works because renaming a file in unix is atomic.
One thing to keep in mind that is that it's only atomic on the same physical device. So writing to /tmp
may not work.