ken_nogi/PythonProj/ScanOCR/スクリプト/lock_manager.py
Kenichiro NOGI 905633541f feat: 二重起動防止ロック管理モジュールを追加
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-02 10:09:32 +09:00

45 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""二重起動防止ロックファイル管理モジュールWindows専用"""
from __future__ import annotations
import ctypes
import os
from pathlib import Path
from typing import Callable
class LockAcquisitionError(Exception):
pass
def _is_pid_running_windows(pid: int) -> bool:
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
if handle:
ctypes.windll.kernel32.CloseHandle(handle)
return True
return False
def acquire_lock(
lock_path: Path,
pid_checker: Callable[[int], bool] = _is_pid_running_windows,
) -> None:
if lock_path.exists():
try:
recorded_pid = int(lock_path.read_text(encoding="utf-8").strip())
except ValueError:
recorded_pid = None
if recorded_pid is not None and pid_checker(recorded_pid):
raise LockAcquisitionError(f"既に実行中ですPID={recorded_pid}")
lock_path.unlink()
lock_path.write_text(str(os.getpid()), encoding="utf-8")
def release_lock(lock_path: Path) -> None:
if lock_path.exists():
lock_path.unlink()