fix: use fcntl file lock to prevent PID file race condition

This commit is contained in:
2026-06-18 15:27:21 +02:00
parent 058de8089c
commit 7e8e915024
2 changed files with 75 additions and 101 deletions
+29 -30
View File
@@ -5,6 +5,7 @@ import pygame
import random
import sys
import os
import fcntl
from common import PID_FILE
@@ -16,44 +17,42 @@ logging.basicConfig(
)
_pid_lock_fd = None
def ensure_single_instance():
"""Ensures that only one instance of the script is running."""
if os.path.exists(PID_FILE):
try:
with open(PID_FILE, 'r') as f:
old_pid = int(f.read().strip())
"""Ensures that only one instance of the script is running.
# Check if the process is still running
os.kill(old_pid, 0)
# If os.kill succeeds, the process is running.
logging.error(f"Another instance of wecker (PID {old_pid}) is already running. Exiting.")
sys.exit(1)
except (ValueError, ProcessLookupError):
# ValueError: PID file is not an integer
# ProcessLookupError: PID doesn't exist
pass
except PermissionError:
# Process exists but we don't have permission to signal it.
logging.error(f"Another instance of wecker (PID {old_pid}) is already running. Exiting.")
sys.exit(1)
except OSError:
# Other OS errors, might mean process is dead
pass
Uses an advisory file lock on the PID file so the check-and-write
sequence is atomic and race-free.
"""
global _pid_lock_fd
_pid_lock_fd = open(PID_FILE, "a+")
try:
fcntl.flock(_pid_lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (BlockingIOError, OSError):
logging.error("Another instance of wecker is already running. Exiting.")
sys.exit(1)
with open(PID_FILE, 'w') as f:
f.write(str(os.getpid()))
_pid_lock_fd.seek(0)
_pid_lock_fd.truncate()
_pid_lock_fd.write(str(os.getpid()))
_pid_lock_fd.flush()
def remove_pid_file():
"""Removes the PID file."""
if os.path.exists(PID_FILE):
"""Releases the PID file lock and removes the file."""
global _pid_lock_fd
if _pid_lock_fd is not None:
try:
with open(PID_FILE, 'r') as f:
current_pid = int(f.read().strip())
if current_pid == os.getpid():
os.remove(PID_FILE)
except (ValueError, OSError):
_pid_lock_fd.close()
except OSError:
pass
_pid_lock_fd = None
try:
os.remove(PID_FILE)
except FileNotFoundError:
pass
# GPIO Setup