Add killTree to recursively kill child processes
This commit is contained in:
parent
10e98e2dc5
commit
cba1ccce6d
28
src/run.ts
28
src/run.ts
|
|
@ -28,6 +28,32 @@ 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 {
|
||||||
|
const descendants = getDescendants(pid)
|
||||||
|
// Kill process group first
|
||||||
|
try { process.kill(-pid, "SIGKILL") } catch {}
|
||||||
|
// Then kill any descendants that escaped the process group
|
||||||
|
for (const d of descendants) {
|
||||||
|
try { process.kill(d, "SIGKILL") } catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const SENTINEL_PREFIX = "__SHOUT_SENTINEL_"
|
const SENTINEL_PREFIX = "__SHOUT_SENTINEL_"
|
||||||
|
|
||||||
function buildScript(commands: Command[], sentinel: string): string {
|
function buildScript(commands: Command[], sentinel: string): string {
|
||||||
|
|
@ -190,7 +216,7 @@ export async function runFile(
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (proc.pid) {
|
if (proc.pid) {
|
||||||
try { process.kill(-proc.pid, "SIGKILL") } catch {}
|
killTree(proc.pid)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user