Skip to content
Draft
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