fixed the ensure one instanve only logic.

This commit is contained in:
Hamed
2025-12-15 20:26:07 +03:30
parent fb12d5a216
commit 4163d1cf6e
2 changed files with 27 additions and 6 deletions

View File

@@ -2,3 +2,4 @@ keyboard==0.13.5
pyperclip==1.9.0
pystray==0.19.5
Pillow==12.0.0
psutil>=5.8.0

View File

@@ -180,15 +180,26 @@ def cleanup_lock():
def is_process_running(pid):
"""Check if a process with the given PID is still running."""
try:
os.kill(pid, 0) # Signal 0 doesn't kill, just checks if process exists
return True
except OSError:
return False
import psutil
return psutil.pid_exists(pid)
except:
# Fallback if psutil is not available
try:
os.kill(pid, 0) # Signal 0 doesn't kill, just checks if process exists
return True
except OSError:
return False
def ensure_single_instance():
"""Ensure only one instance of the app is running. Exit if another instance exists."""
if os.path.exists(LOCK_FILE):
try:
# Read the PID from the lock file
with open(LOCK_FILE, 'r') as f:
old_pid = int(f.read().strip())
# Check if the process with that PID is still running
if is_process_running(old_pid):
# Another instance is running, show message and exit
import ctypes
ctypes.windll.user32.MessageBoxW(
@@ -198,9 +209,18 @@ def ensure_single_instance():
0x40 # MB_ICONINFORMATION
)
os._exit(1)
else:
# Process is not running, remove the stale lock file
try:
os.remove(LOCK_FILE)
except OSError:
pass
except (ValueError, OSError):
# Lock file exists but is invalid or unreadable, clean it up
pass
# Lock file exists but is invalid or unreadable, clean it up and continue
try:
os.remove(LOCK_FILE)
except OSError:
pass
# Create lock file with our PID
with open(LOCK_FILE, 'w') as f: