Kill processes that are listening on the given port. Uses multiple methods to ensure thorough cleanup.
(port: int)
| 110 | |
| 111 | |
| 112 | def kill_process_on_port(port: int): |
| 113 | """ |
| 114 | Kill processes that are listening on the given port. |
| 115 | Uses multiple methods to ensure thorough cleanup. |
| 116 | """ |
| 117 | current_pid = os.getpid() |
| 118 | parent_pid = os.getppid() |
| 119 | |
| 120 | # Method 1: Use lsof to find processes |
| 121 | try: |
| 122 | output = subprocess.check_output(f"lsof -i:{port} -t", shell=True).decode().strip() |
| 123 | for pid in output.splitlines(): |
| 124 | pid = int(pid) |
| 125 | if pid in (current_pid, parent_pid): |
| 126 | print(f"Skip killing current process (pid={pid}) on port {port}") |
| 127 | continue |
| 128 | try: |
| 129 | # First try SIGTERM for graceful shutdown |
| 130 | os.kill(pid, signal.SIGTERM) |
| 131 | time.sleep(1) |
| 132 | # Then SIGKILL if still running |
| 133 | os.kill(pid, signal.SIGKILL) |
| 134 | print(f"Killed process on port {port}, pid={pid}") |
| 135 | except ProcessLookupError: |
| 136 | pass # Process already terminated |
| 137 | except subprocess.CalledProcessError: |
| 138 | pass |
| 139 | |
| 140 | # Method 2: Use netstat and fuser as backup |
| 141 | try: |
| 142 | # Find processes using netstat and awk |
| 143 | cmd = f"netstat -tulpn 2>/dev/null | grep :{port} | awk '{{print $7}}' | cut -d'/' -f1" |
| 144 | output = subprocess.check_output(cmd, shell=True).decode().strip() |
| 145 | for pid in output.splitlines(): |
| 146 | if pid and pid.isdigit(): |
| 147 | pid = int(pid) |
| 148 | if pid in (current_pid, parent_pid): |
| 149 | continue |
| 150 | try: |
| 151 | os.kill(pid, signal.SIGKILL) |
| 152 | print(f"Killed process (netstat) on port {port}, pid={pid}") |
| 153 | except ProcessLookupError: |
| 154 | pass |
| 155 | except (subprocess.CalledProcessError, FileNotFoundError): |
| 156 | pass |
| 157 | |
| 158 | # Method 3: Use fuser if available |
| 159 | try: |
| 160 | subprocess.run(f"fuser -k {port}/tcp", shell=True, timeout=5) |
| 161 | except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError): |
| 162 | pass |
| 163 | |
| 164 | |
| 165 | def clean_ports(ports_to_clean: list[int]): |
no test coverage detected