Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/filelock/_unix.py: 67%
39 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 07:11 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 07:11 +0000
1from __future__ import annotations
3import os
4import sys
5from errno import ENOSYS
6from typing import cast
8from ._api import BaseFileLock
10#: a flag to indicate if the fcntl API is available
11has_fcntl = False
12if sys.platform == "win32": # pragma: win32 cover
14 class UnixFileLock(BaseFileLock):
15 """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
17 def _acquire(self) -> None:
18 raise NotImplementedError
20 def _release(self) -> None:
21 raise NotImplementedError
23else: # pragma: win32 no cover
24 try:
25 import fcntl
26 except ImportError:
27 pass
28 else:
29 has_fcntl = True
31 class UnixFileLock(BaseFileLock):
32 """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
34 def _acquire(self) -> None:
35 open_flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC
36 fd = os.open(self.lock_file, open_flags, self._context.mode)
37 try:
38 os.fchmod(fd, self._context.mode)
39 except PermissionError:
40 pass # This locked is not owned by this UID
41 try:
42 fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
43 except OSError as exception:
44 os.close(fd)
45 if exception.errno == ENOSYS: # NotImplemented error
46 raise NotImplementedError("FileSystem does not appear to support flock; user SoftFileLock instead")
47 else:
48 self._context.lock_file_fd = fd
50 def _release(self) -> None:
51 # Do not remove the lockfile:
52 # https://github.com/tox-dev/py-filelock/issues/31
53 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
54 fd = cast(int, self._context.lock_file_fd)
55 self._context.lock_file_fd = None
56 fcntl.flock(fd, fcntl.LOCK_UN)
57 os.close(fd)
60__all__ = [
61 "has_fcntl",
62 "UnixFileLock",
63]