Many common filesystems do not offer atomic operations, yet writing files in an atomic manner is very important in certain scenarios. I tried to come up with a solution for this problem.
I made the following assumptions:
This leaves the following problem: While writing a file, the program could be interrupted and the file would be left with only a part of the content to write.
I propose the following process:
New and Backup files are distinguishable from Original files (for instance, they could be prefixed differently, or could be in a separate directory on the same volume). At the same time, their name should map directly to the corresponding Original (for instance by simply using the same file name).
This, however, does not make the operation atomic yet. The process could be interrupted steps 1, 2, 3 or 4:
Using assumptions 2 and 3 from earlier, the program has to be restarted after a crash. During the startup process, it should perform these recovery checks:
The recovery process itself, only using atomic operations, will simply continue where it left off after being interrupted.
I believe this idea ensures atomic writes for a single program. These issues exist still:
Those issues (which are excluded by the assumptions earlier) could be solved via usage policy (for instance, check for other instances, and deny directory access to other users).
Finally, my question: Did that make sense, or is there a flaw in the process? Are there any issues that prevent this approach from being used in practice?
There is only one thing you should assume, renaming a file is atomic operation
So following steps will ensure correction (at least on unix like OS)
This way if application crashed when restarted it either get the old content or new content without need of extra code.
Your steps can be simplified further:
On startup:
I have used this in managing configuration files and have never encountered a problem from this process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With