Skip to content

Enable removal of UNIX lock files #408

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions src/filelock/_unix.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,21 @@ def _acquire(self) -> None:
msg = "FileSystem does not appear to support flock; use SoftFileLock instead"
raise NotImplementedError(msg) from exception
else:
self._context.lock_file_fd = fd
st = os.fstat(fd)
if st.st_nlink == 0:
# We raced with another process that deleted the lock file
# before we called fcntl.flock. This means that lock is not
# valid (since another process will just lock a different
# file) and we need to try again.
# See https://stackoverflow.com/a/51070775
os.close(fd)
else:
self._context.lock_file_fd = fd

def _release(self) -> None:
# Do not remove the lockfile:
# https://github.com/tox-dev/py-filelock/issues/31
# https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
fd = cast("int", self._context.lock_file_fd)
self._context.lock_file_fd = None
Path.unlink(self.lock_file)
fcntl.flock(fd, fcntl.LOCK_UN)
os.close(fd)

Expand Down