mirror of
https://github.com/IgorAherne/Spellcast3d.git
synced 2026-12-01 08:06:27 -10:00
55 lines
1.7 KiB
Python
55 lines
1.7 KiB
Python
"""A lock on a file, held by a process for as long as it keeps the file open. The system releases it when the process
|
|
dies, so it never goes stale: the installer's lock (install/main.py) and the running hub's (__main__.py).
|
|
|
|
Windows locks the file's first byte (msvcrt); elsewhere the whole file is locked with flock - not with POSIX record
|
|
locks, which a process may take twice and loses when it closes any other handle of the file.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from pathlib import Path
|
|
from typing import IO
|
|
|
|
if os.name == "nt":
|
|
import msvcrt
|
|
|
|
def take(f: IO[bytes]) -> bool:
|
|
"""Lock the open file without waiting -> False when another holder has it."""
|
|
f.seek(0)
|
|
try:
|
|
msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
|
|
except OSError:
|
|
return False
|
|
return True
|
|
|
|
def release(f: IO[bytes]) -> None:
|
|
f.seek(0)
|
|
msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
|
|
else:
|
|
import fcntl
|
|
|
|
def take(f: IO[bytes]) -> bool:
|
|
"""Lock the open file without waiting -> False when another holder has it."""
|
|
try:
|
|
fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except OSError:
|
|
return False
|
|
return True
|
|
|
|
def release(f: IO[bytes]) -> None:
|
|
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
|
|
|
|
|
|
def held(lock_file: Path) -> bool:
|
|
"""True while another process (or another open handle of this one) holds lock_file."""
|
|
try:
|
|
f = open(lock_file, "a+b")
|
|
except OSError:
|
|
return False # no folder yet, or not ours to open: nothing is running from it
|
|
with f:
|
|
if not take(f):
|
|
return True
|
|
release(f)
|
|
return False
|