"""Cross-process ownership of the game during tasks and module conversion.""" import errno import os from contextlib import contextmanager class GameBusyError(RuntimeError): pass def default_lock_path(): return os.path.expanduser('~/lc_mcp/game.lock') @contextmanager def exclusive_game(path=None): """Acquire without waiting; closing the file also releases a crashed owner's lock. Keep the file in place: unlinking it would let another process lock a different inode. The OS owns the lock, so a leftover file is not a stale reservation. """ path = os.path.abspath(path or default_lock_path()) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, 'a+b') as lock: lock.seek(0) try: if os.name == 'nt': import msvcrt msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError as e: if e.errno in (errno.EACCES, errno.EAGAIN, errno.EDEADLK): raise GameBusyError('游戏正由其他任务或合成脚本使用,本次不接管') from e raise try: yield finally: if os.name == 'nt': lock.seek(0) msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) else: fcntl.flock(lock.fileno(), fcntl.LOCK_UN)