kill escaped procs inline, guard pid > 1

This commit is contained in:
Chris Wanstrath 2026-03-12 15:14:21 -07:00
parent 9b739fd8e4
commit 9d13dfa5e7

View File

@ -29,23 +29,22 @@ type RunOptions = {
}
function killTree(pid: number): void {
// Find any processes that escaped the process group (e.g. via setsid)
// using a single cross-platform ps call, then kill them before the group.
// Find any processes that escaped the process group (e.g. via setsid).
// This assumes pid === pgid, which holds because the child is spawned
// with detached: true (making it a process group leader).
try {
const result = Bun.spawnSync(["ps", "-eo", "pid,pgid"])
const output = result.stdout.toString()
const pgid = String(pid)
const escapees: number[] = []
for (const line of output.split("\n")) {
const parts = line.trim().split(/\s+/)
if (parts[1] === pgid) {
const p = parseInt(parts[0]!, 10)
if (!isNaN(p) && p !== pid) escapees.push(p)
if (!isNaN(p) && p !== pid && p > 1) {
try { process.kill(p, "SIGKILL") } catch {}
}
}
}
for (const p of escapees) {
try { process.kill(p, "SIGKILL") } catch {}
}
} catch {}
// Kill the process group
try { process.kill(-pid, "SIGKILL") } catch {}