I'm using the filelock
module for Python.
On Windows, when a lock is released, the file that's backing it is deleted.
On UNIX, lock files still exist on the filesystem even after the locks are released.
Is there a reason this is different between operating systems? If there isn't a reason for it to differ, which of these behaviors is more correct?
py-filelock
The filelock
library used to delete lockfiles on UNIX; this behavior was removed as of benediktschmitt/py-filelock#31
, which refers to flock(): removing locked file without race condition? -- which discusses the same race condition described in a later section of this answer.
The operating-system semantics are different, so different approaches are appropriate in each case. In UNIX, you can delete a file even while there's an open handle, so lockfiles must not be deleted or else two programs can both think they hold the same lock, when in fact they hold locks on completely different inodes which were, at different points in time, referenced under the same filename.
By contrast, default filesystem semantics on Windows make it impossible to delete a file while any program has it open (even though NTFS is powerful enough to support it, it's artificially prevented for backwards compatibility with programs designed around FAT limitations), so on Windows, it's safe to delete a lockfile: If the deletion goes through, that proves that nobody held the lock (or was even in the process of opening the file to later grab a lock on it).
To provide an example of how allowing open files to be unlinked on UNIX makes deleting lockfiles dangerous, consider the following illustration of a common race condition:
unlink()
syscall to delete the lockfile. (To be safe on UNIX, just leave this step out). This doesn't delete the file itself (the "inode") until no programs have it open, but it does immediately delete the link to that file from the directory that previously contained it.Consequently, the above illustrates how on UNIX, deleting lockfiles allows race conditions wherein a lock can appear to be held by two programs at once.
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