(options: KillOptions)
| 36 | * to ensure all descendants are killed. |
| 37 | */ |
| 38 | export async function killProcessGroup(options: KillOptions): Promise<void> { |
| 39 | const { pid, escalate = false, isExited = () => false, pty } = options; |
| 40 | const isWindows = os.platform() === 'win32'; |
| 41 | |
| 42 | if (isWindows) { |
| 43 | if (pty) { |
| 44 | try { |
| 45 | pty.kill(); |
| 46 | } catch { |
| 47 | // Ignore errors for dead processes |
| 48 | } |
| 49 | } |
| 50 | // Invoke taskkill to ensure the entire tree is terminated and any orphaned descendant processes are reaped. |
| 51 | try { |
| 52 | await spawnAsync('taskkill', ['/pid', pid.toString(), '/f', '/t']); |
| 53 | } catch { |
| 54 | // Ignore errors if the process tree is already dead |
| 55 | } |
| 56 | return; |
| 57 | } |
| 58 | |
| 59 | // Unix logic: Walk process tree to find all descendants |
| 60 | const getAllDescendants = async (parentPid: number): Promise<number[]> => { |
| 61 | let children: number[] = []; |
| 62 | try { |
| 63 | const { stdout } = await spawnAsync('pgrep', [ |
| 64 | '-P', |
| 65 | parentPid.toString(), |
| 66 | ]); |
| 67 | const pids = stdout |
| 68 | .trim() |
| 69 | .split('\n') |
| 70 | .map((p: string) => parseInt(p, 10)) |
| 71 | .filter((p: number) => !isNaN(p)); |
| 72 | for (const p of pids) { |
| 73 | children.push(p); |
| 74 | const grandchildren = await getAllDescendants(p); |
| 75 | children = children.concat(grandchildren); |
| 76 | } |
| 77 | } catch { |
| 78 | // pgrep exits with 1 if no children are found |
| 79 | } |
| 80 | return children; |
| 81 | }; |
| 82 | |
| 83 | const descendants = await getAllDescendants(pid); |
| 84 | const allPidsToKill = [...descendants.reverse(), pid]; |
| 85 | |
| 86 | try { |
| 87 | const initialSignal = options.signal || (escalate ? 'SIGTERM' : 'SIGKILL'); |
| 88 | |
| 89 | // Try killing the process group first (-pid) |
| 90 | try { |
| 91 | process.kill(-pid, initialSignal); |
| 92 | } catch { |
| 93 | // Ignore |
| 94 | } |
| 95 |
no test coverage detected