"""Per-device advisory process lock: same-user GUI and CLI cannot race.""" import os from pathlib import Path class DeviceAlreadyRunning(RuntimeError): pass class DeviceProcessLock: def __init__(self, directory): self.path = Path(directory) / "bridge.lock" self.file = None def __enter__(self): self.path.parent.mkdir(parents=True, exist_ok=True) self.file = self.path.open("a+b") self.file.seek(0, 2) if self.file.tell() == 0: self.file.write(b"0") self.file.flush() self.file.seek(0) try: if os.name == "nt": import msvcrt msvcrt.locking(self.file.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(self.file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: self.file.close() self.file = None raise DeviceAlreadyRunning("该设备已有桥接进程运行,请勿重复启动。") from None return self def __exit__(self, *args): if self.file: self.file.seek(0) if os.name == "nt": import msvcrt msvcrt.locking(self.file.fileno(), msvcrt.LK_UNLCK, 1) else: import fcntl fcntl.flock(self.file.fileno(), fcntl.LOCK_UN) self.file.close() self.file = None