How to safely maintain a status file

Nobody nobody at nowhere.com
Mon Jul 9 04:57:15 EDT 2012


On Sun, 08 Jul 2012 22:57:56 +0200, Laszlo Nagy wrote:

> Yes, this is much better. Almost perfect. Don't forget to consult your
> system documentation, and check if the rename operation is atomic or not.
> (Most probably it will only be atomic if the original and the renamed file
> are on the same physical partition and/or mount point).

On Unix, rename() is always atomic, and requires that source and
destination are on the same partition (if you want to "move" a file across
partitions, you have to copy it then delete the original).

> But even if the rename operation is atomic, there is still a race
> condition. Your program can be terminated after the original status file
> has been deleted, and before the temp file was renamed. In this case, you
> will be missing the status file (although your program already did
> something just it could not write out the new status).

In the event of abnormal termination, losing some data is to be expected.
The idea is to only lose the most recent data while keeping the old copy,
rather than losing everything. Writing to a temp file then rename()ing
achieves that.




More information about the Python-list mailing list