diff --git a/requirements.txt b/requirements.txt index 27542e7..5f3da91 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ keyboard==0.13.5 pyperclip==1.9.0 pystray==0.19.5 Pillow==12.0.0 +psutil>=5.8.0 diff --git a/src/main.pyw b/src/main.pyw index 5f877f3..01a5a7b 100644 --- a/src/main.pyw +++ b/src/main.pyw @@ -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: