-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_manager.py
More file actions
65 lines (53 loc) · 1.79 KB
/
Copy pathprocess_manager.py
File metadata and controls
65 lines (53 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python3
"""
Process Management Script
Ensures a clean environment by gracefully terminating old instances of the application.
"""
import os
import sys
import time
import signal
import subprocess
import psutil
TARGET_SCRIPT = "main_enhanced.py"
def get_target_processes():
"""Find all processes running the target script."""
procs = []
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
cmdline = proc.info['cmdline']
if cmdline and any(TARGET_SCRIPT in arg for arg in cmdline):
procs.append(proc)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return procs
def kill_processes():
"""Terminate target processes gracefully, then forcefully."""
procs = get_target_processes()
if not procs:
print(f"✅ No existing instances of {TARGET_SCRIPT} found.")
return
print(f"⚠️ Found {len(procs)} running instances of {TARGET_SCRIPT}. Cleaning up...")
# 1. Graceful Shutdown (SIGTERM)
for proc in procs:
try:
print(f" - Sending SIGTERM to PID {proc.pid}...")
proc.terminate()
except psutil.NoSuchProcess:
pass
# Wait for them to exit
gone, alive = psutil.wait_procs(procs, timeout=5)
# 2. Force Kill (SIGKILL)
if alive:
print(f"⚠️ {len(alive)} processes did not exit. Force killing...")
for proc in alive:
try:
print(f" - Sending SIGKILL to PID {proc.pid}...")
proc.kill()
except psutil.NoSuchProcess:
pass
# Wait again to be sure
psutil.wait_procs(alive, timeout=2)
print("✅ Cleanup complete.")
if __name__ == "__main__":
kill_processes()