26 lines
739 B
Python
26 lines
739 B
Python
"""One machine-wide lock for processes that consume the recording inbox."""
|
|
from __future__ import annotations
|
|
|
|
import fcntl
|
|
import os
|
|
from pathlib import Path
|
|
|
|
|
|
def acquire_recording_lock(path: Path):
|
|
"""Return an open file holding an exclusive lock, or exit if another consumer has it.
|
|
|
|
The handle must stay referenced for the life of the process.
|
|
"""
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
handle = path.open("a+")
|
|
try:
|
|
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except OSError:
|
|
handle.close()
|
|
raise SystemExit(f"another recording consumer holds {path}")
|
|
handle.seek(0)
|
|
handle.truncate()
|
|
handle.write(str(os.getpid()))
|
|
handle.flush()
|
|
return handle
|