Kill any runner.exe / example_runner.exe processes under *build_dir*. Iterates running processes (via ``psutil``) and terminates any whose name matches a known runner binary AND whose executable path resolves to somewhere under ``build_dir``. This avoids killing unrelated processes
(build_dir: Path)
| 64 | |
| 65 | |
| 66 | def kill_stale_runner_processes(build_dir: Path) -> int: |
| 67 | """Kill any runner.exe / example_runner.exe processes under *build_dir*. |
| 68 | |
| 69 | Iterates running processes (via ``psutil``) and terminates any whose name |
| 70 | matches a known runner binary AND whose executable path resolves to |
| 71 | somewhere under ``build_dir``. This avoids killing unrelated processes |
| 72 | with the same name that happen to be running on the machine. |
| 73 | |
| 74 | Returns the number of processes killed. No-op and returns 0 on non-Windows. |
| 75 | |
| 76 | Safe to call when psutil is not importable — returns 0 silently. |
| 77 | """ |
| 78 | if sys.platform != "win32": |
| 79 | return 0 |
| 80 | |
| 81 | try: |
| 82 | import psutil # noqa: PLC0415 - lazy import, Windows-only helper |
| 83 | except ImportError: |
| 84 | return 0 |
| 85 | |
| 86 | try: |
| 87 | build_root = str(build_dir.resolve()) |
| 88 | except OSError: |
| 89 | return 0 |
| 90 | |
| 91 | killed = 0 |
| 92 | for proc in psutil.process_iter(["pid", "name", "exe"]): |
| 93 | try: |
| 94 | name = (proc.info.get("name") or "").lower() |
| 95 | if name not in _RUNNER_NAMES: |
| 96 | continue |
| 97 | |
| 98 | exe = proc.info.get("exe") |
| 99 | if not exe: |
| 100 | continue |
| 101 | |
| 102 | # Only terminate runners launched from *our* build directory. |
| 103 | try: |
| 104 | exe_resolved = str(Path(exe).resolve()) |
| 105 | except OSError: |
| 106 | continue |
| 107 | |
| 108 | if exe_resolved == build_root or exe_resolved.startswith( |
| 109 | build_root + os.sep |
| 110 | ): |
| 111 | proc.kill() |
| 112 | killed += 1 |
| 113 | except (psutil.NoSuchProcess, psutil.AccessDenied, OSError): |
| 114 | continue |
| 115 | |
| 116 | return killed |