Simplify killTree with single ps call
This commit is contained in:
parent
cba1ccce6d
commit
9b739fd8e4
41
src/run.ts
41
src/run.ts
|
|
@ -28,31 +28,28 @@ type RunOptions = {
|
||||||
onCommand?: (cmd: Command) => void
|
onCommand?: (cmd: Command) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
function getDescendants(pid: number): number[] {
|
|
||||||
try {
|
|
||||||
const result = Bun.spawnSync(["ps", "-o", "pid=", "--ppid", String(pid)])
|
|
||||||
const output = new TextDecoder().decode(result.stdout)
|
|
||||||
const children = output.trim().split("\n").filter(Boolean).map(s => parseInt(s.trim(), 10)).filter(n => !isNaN(n))
|
|
||||||
const all: number[] = []
|
|
||||||
for (const child of children) {
|
|
||||||
all.push(...getDescendants(child))
|
|
||||||
all.push(child)
|
|
||||||
}
|
|
||||||
return all
|
|
||||||
} catch {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function killTree(pid: number): void {
|
function killTree(pid: number): void {
|
||||||
const descendants = getDescendants(pid)
|
// Find any processes that escaped the process group (e.g. via setsid)
|
||||||
// Kill process group first
|
// using a single cross-platform ps call, then kill them before the group.
|
||||||
try { process.kill(-pid, "SIGKILL") } catch {}
|
try {
|
||||||
// Then kill any descendants that escaped the process group
|
const result = Bun.spawnSync(["ps", "-eo", "pid,pgid"])
|
||||||
for (const d of descendants) {
|
const output = result.stdout.toString()
|
||||||
try { process.kill(d, "SIGKILL") } catch {}
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for (const p of escapees) {
|
||||||
|
try { process.kill(p, "SIGKILL") } catch {}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
// Kill the process group
|
||||||
|
try { process.kill(-pid, "SIGKILL") } catch {}
|
||||||
|
}
|
||||||
|
|
||||||
const SENTINEL_PREFIX = "__SHOUT_SENTINEL_"
|
const SENTINEL_PREFIX = "__SHOUT_SENTINEL_"
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user