|
| 1 | +import { spawnSync } from "child_process"; |
| 2 | + |
| 3 | +type TaskkillSpawnSync = ( |
| 4 | + command: string, |
| 5 | + args: string[], |
| 6 | + options: { stdio: "ignore"; windowsHide: true } |
| 7 | +) => { status: number | null; error?: Error }; |
| 8 | + |
| 9 | +export type KillProcessTreeDeps = { |
| 10 | + platform?: NodeJS.Platform; |
| 11 | + killPid?: (pid: number, signal: NodeJS.Signals) => void; |
| 12 | + runTaskkill?: (pid: number) => boolean; |
| 13 | + killGroupOnNonWindows?: boolean; |
| 14 | +}; |
| 15 | + |
| 16 | +export function killProcessTree( |
| 17 | + pid: number, |
| 18 | + signal: NodeJS.Signals = "SIGKILL", |
| 19 | + deps: KillProcessTreeDeps = {} |
| 20 | +): boolean { |
| 21 | + if (!Number.isInteger(pid) || pid <= 0) { |
| 22 | + return false; |
| 23 | + } |
| 24 | + |
| 25 | + const platform = deps.platform ?? process.platform; |
| 26 | + const killPid = deps.killPid ?? ((targetPid, targetSignal) => process.kill(targetPid, targetSignal)); |
| 27 | + |
| 28 | + if (platform === "win32") { |
| 29 | + const runTaskkill = deps.runTaskkill ?? runWindowsTaskkill; |
| 30 | + if (runTaskkill(pid)) { |
| 31 | + return true; |
| 32 | + } |
| 33 | + return killDirectProcess(pid, signal, killPid); |
| 34 | + } |
| 35 | + |
| 36 | + if (deps.killGroupOnNonWindows !== false && killDirectProcess(-pid, signal, killPid)) { |
| 37 | + return true; |
| 38 | + } |
| 39 | + return killDirectProcess(pid, signal, killPid); |
| 40 | +} |
| 41 | + |
| 42 | +export function runWindowsTaskkill(pid: number, spawnSyncImpl: TaskkillSpawnSync = spawnSync): boolean { |
| 43 | + const result = spawnSyncImpl("taskkill", ["/PID", String(pid), "/T", "/F"], { |
| 44 | + stdio: "ignore", |
| 45 | + windowsHide: true, |
| 46 | + }); |
| 47 | + return !result.error && result.status === 0; |
| 48 | +} |
| 49 | + |
| 50 | +function killDirectProcess( |
| 51 | + pid: number, |
| 52 | + signal: NodeJS.Signals, |
| 53 | + killPid: (pid: number, signal: NodeJS.Signals) => void |
| 54 | +): boolean { |
| 55 | + try { |
| 56 | + killPid(pid, signal); |
| 57 | + return true; |
| 58 | + } catch { |
| 59 | + return false; |
| 60 | + } |
| 61 | +} |
0 commit comments