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 { function killTree(pid: number): void {
// Find any processes that escaped the process group (e.g. via setsid) // 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. // This assumes pid === pgid, which holds because the child is spawned
// with detached: true (making it a process group leader).
try { try {
const result = Bun.spawnSync(["ps", "-eo", "pid,pgid"]) const result = Bun.spawnSync(["ps", "-eo", "pid,pgid"])
const output = result.stdout.toString() const output = result.stdout.toString()
const pgid = String(pid) const pgid = String(pid)
const escapees: number[] = []
for (const line of output.split("\n")) { for (const line of output.split("\n")) {
const parts = line.trim().split(/\s+/) const parts = line.trim().split(/\s+/)
if (parts[1] === pgid) { if (parts[1] === pgid) {
const p = parseInt(parts[0]!, 10) 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 {} } catch {}
// Kill the process group // Kill the process group
try { process.kill(-pid, "SIGKILL") } catch {} try { process.kill(-pid, "SIGKILL") } catch {}