Kill processes by PID. Args: pids: Set of process IDs to kill force: If True, use SIGKILL (Windows: TerminateProcess), otherwise SIGTERM Returns: True if all processes were killed successfully
(pids: set[int], force: bool = True)
| 147 | |
| 148 | |
| 149 | def kill_processes(pids: set[int], force: bool = True) -> bool: |
| 150 | """Kill processes by PID. |
| 151 | |
| 152 | Args: |
| 153 | pids: Set of process IDs to kill |
| 154 | force: If True, use SIGKILL (Windows: TerminateProcess), otherwise SIGTERM |
| 155 | |
| 156 | Returns: |
| 157 | True if all processes were killed successfully |
| 158 | """ |
| 159 | if not pids: |
| 160 | return True |
| 161 | |
| 162 | if not is_psutil_available(): |
| 163 | print("Warning: psutil not available, cannot kill processes") |
| 164 | return False |
| 165 | |
| 166 | all_killed = True |
| 167 | |
| 168 | for pid in pids: |
| 169 | try: |
| 170 | proc = psutil.Process(pid) |
| 171 | proc_name = proc.name() |
| 172 | |
| 173 | print(f" Killing process {pid} ({proc_name})...") |
| 174 | |
| 175 | if force: |
| 176 | proc.kill() # SIGKILL on Unix, TerminateProcess on Windows |
| 177 | else: |
| 178 | proc.terminate() # SIGTERM on Unix, gentle termination on Windows |
| 179 | |
| 180 | # Wait for process to die (with timeout) |
| 181 | try: |
| 182 | proc.wait(timeout=3) |
| 183 | print(f" ✓ Process {pid} terminated successfully") |
| 184 | except psutil.TimeoutExpired: |
| 185 | print(f" ⚠ Process {pid} did not terminate within timeout, forcing...") |
| 186 | proc.kill() |
| 187 | proc.wait(timeout=1) |
| 188 | print(f" ✓ Process {pid} force-killed") |
| 189 | |
| 190 | except psutil.NoSuchProcess: |
| 191 | print(f" ✓ Process {pid} already terminated") |
| 192 | except psutil.AccessDenied: |
| 193 | print( |
| 194 | f" ✗ Access denied killing process {pid} (may require admin privileges)" |
| 195 | ) |
| 196 | all_killed = False |
| 197 | except KeyboardInterrupt as ki: |
| 198 | handle_keyboard_interrupt(ki) |
| 199 | raise |
| 200 | except Exception as e: |
| 201 | print(f" ✗ Failed to kill process {pid}: {e}") |
| 202 | all_killed = False |
| 203 | |
| 204 | # Give system time to release file handles |
| 205 | if pids: |
| 206 | time.sleep(0.5) |
no test coverage detected