Kill processes that are listening on the given port. Uses multiple methods to ensure thorough cleanup.
(port: int)
| 41 | |
| 42 | |
| 43 | def kill_process_on_port(port: int): |
| 44 | """ |
| 45 | Kill processes that are listening on the given port. |
| 46 | Uses multiple methods to ensure thorough cleanup. |
| 47 | """ |
| 48 | current_pid = os.getpid() |
| 49 | parent_pid = os.getppid() |
| 50 | |
| 51 | # Method 1: Use lsof to find processes |
| 52 | try: |
| 53 | output = subprocess.check_output(f"lsof -i:{port} -t", shell=True).decode().strip() |
| 54 | for pid in output.splitlines(): |
| 55 | pid = int(pid) |
| 56 | if pid in (current_pid, parent_pid): |
| 57 | print(f"Skip killing current process (pid={pid}) on port {port}") |
| 58 | continue |
| 59 | try: |
| 60 | # First try SIGTERM for graceful shutdown |
| 61 | os.kill(pid, signal.SIGTERM) |
| 62 | time.sleep(1) |
| 63 | # Then SIGKILL if still running |
| 64 | os.kill(pid, signal.SIGKILL) |
| 65 | print(f"Killed process on port {port}, pid={pid}") |
| 66 | except ProcessLookupError: |
| 67 | pass # Process already terminated |
| 68 | except subprocess.CalledProcessError: |
| 69 | pass |
| 70 | |
| 71 | # Method 2: Use netstat and fuser as backup |
| 72 | try: |
| 73 | # Find processes using netstat and awk |
| 74 | cmd = f"netstat -tulpn 2>/dev/null | grep :{port} | awk '{{print $7}}' | cut -d'/' -f1" |
| 75 | output = subprocess.check_output(cmd, shell=True).decode().strip() |
| 76 | for pid in output.splitlines(): |
| 77 | if pid and pid.isdigit(): |
| 78 | pid = int(pid) |
| 79 | if pid in (current_pid, parent_pid): |
| 80 | continue |
| 81 | try: |
| 82 | os.kill(pid, signal.SIGKILL) |
| 83 | print(f"Killed process (netstat) on port {port}, pid={pid}") |
| 84 | except ProcessLookupError: |
| 85 | pass |
| 86 | except (subprocess.CalledProcessError, FileNotFoundError): |
| 87 | pass |
| 88 | |
| 89 | # Method 3: Use fuser if available |
| 90 | try: |
| 91 | subprocess.run(f"fuser -k {port}/tcp", shell=True, timeout=5) |
| 92 | except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError): |
| 93 | pass |
| 94 | |
| 95 | |
| 96 | def clean_ports(ports=None): |
no test coverage detected