Files
Crypto_Scam/LinuxServer/runtime_lock.py
T
listik efd4e1dcf4
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
linux
2026-10-23 21:36:08 +03:00

46 lines
1.5 KiB
Python

"""One trading engine per data directory, even with different HTTP ports."""
from __future__ import annotations
import os
from pathlib import Path
class RuntimeLock:
def __init__(self, path: Path):
self.path = Path(path)
self.stream = None
def __enter__(self):
self.path.parent.mkdir(parents=True, exist_ok=True)
stream = self.path.open("a+b")
if stream.seek(0, os.SEEK_END) == 0:
stream.write(b"\0")
stream.flush()
stream.seek(0)
try:
if os.name == "nt":
import msvcrt
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
stream.close()
raise RuntimeError("Движок уже запущен для этой папки. Откройте существующее окно программы.") from None
self.stream = stream
return self
def __exit__(self, *args):
if self.stream is not None:
try:
self.stream.seek(0)
if os.name == "nt":
import msvcrt
msvcrt.locking(self.stream.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(self.stream.fileno(), fcntl.LOCK_UN)
finally:
self.stream.close()
self.stream = None