Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions src/lib/tree-kill/tree-kill.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { execFileSync, spawn } from "node:child_process";
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";

import { treeKill } from "./tree-kill";

const isAlive = (pid: number): boolean => {
// A zombie is dead for our purposes: it cannot run anymore, it is only waiting
// for its (possibly also killed) parent to reap it.
try {
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0] !== "Z";
} catch {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
};

const childPids = (pid: number): number[] => {
try {
const out =
process.platform === "darwin"
? execFileSync("pgrep", ["-P", String(pid)], { encoding: "utf8" })
: execFileSync("ps", ["-o", "pid", "--no-headers", "--ppid", String(pid)], {
encoding: "utf8",
});
return out.split(/\s+/).filter(Boolean).map(Number);
} catch {
return [];
}
};

const waitFor = async (condition: () => boolean, timeoutMs = 15_000): Promise<void> => {
const deadline = Date.now() + timeoutMs;
while (!condition()) {
if (Date.now() > deadline) throw new Error("Timed out waiting for the process tree.");
await new Promise((resolve) => setTimeout(resolve, 50));
}
};

describe.skipIf(process.platform === "win32")("treeKill", () => {
it("kills a two-level process tree", { timeout: 30_000 }, async () => {
// A root shell running a child shell that runs `sleep`: two levels to kill.
const root = spawn("sh", ["-c", "sh -c 'sleep 300 & wait' & wait"], { stdio: "ignore" });
const rootPid = root.pid as number;

let descendants: number[] = [];
await waitFor(() => {
descendants = childPids(rootPid).flatMap((child) => [child, ...childPids(child)]);
return descendants.length >= 2;
});
expect(isAlive(rootPid)).toBe(true);
for (const pid of descendants) expect(isAlive(pid)).toBe(true);

await treeKill(rootPid, "SIGKILL");

await waitFor(() => !isAlive(rootPid) && descendants.every((pid) => !isAlive(pid)));
});

it("resolves when the process is already dead", { timeout: 30_000 }, async () => {
const dead = spawn("sh", ["-c", "exit 0"], { stdio: "ignore" });
await new Promise((resolve) => dead.on("exit", resolve));
await expect(treeKill(dead.pid as number, "SIGTERM")).resolves.toBeUndefined();
});
});
163 changes: 76 additions & 87 deletions src/lib/tree-kill/tree-kill.ts
Original file line number Diff line number Diff line change
@@ -1,116 +1,105 @@
import { type ChildProcessWithoutNullStreams, execSync, spawn } from "node:child_process";

export const treeKill = (pid: number, signal: NodeJS.Signals): Promise<void> => {
function extracted(resolve: any) {
const tree: { [key: number]: number[] } = {};
const pidsToProcess: { [key: number]: number } = {};
tree[pid] = [];
pidsToProcess[pid] = 1;
type ProcessTree = { [key: number]: number[] };

switch (process.platform) {
case "win32":
execSync("taskkill /pid " + pid + " /T /F");
resolve();
break;
case "darwin":
buildProcessTree(
pid,
tree,
pidsToProcess,
function (parentPid: string) {
return spawn("pgrep", ["-P", parentPid]);
},
function () {
killAll(tree, signal);
resolve();
},
);
break;
default: // Linux
buildProcessTree(
pid,
tree,
pidsToProcess,
function (parentPid: string) {
return spawn("ps", ["-o", "pid", "--no-headers", "--ppid", parentPid]);
},
function () {
killAll(tree, signal);
resolve();
},
);
break;
}
}
return new Promise((resolve) => {
extracted(resolve);
});
};

function killAll(tree: { [key: number]: number[] }, signal: NodeJS.Signals) {
const killed: { [key: number]: boolean } = {};
Object.keys(tree)
.reverse()
.forEach(function (pidStr) {
const pid = Number(pidStr);
tree[pid]?.forEach(function (pidpid: number) {
if (!killed[pidpid]) {
killPid(pidpid, signal);
killed[pidpid] = true;
}
});
if (!killed[pid]) {
killPid(pid, signal);
killed[pid] = true;
}
});
}

function killPid(pid: number, signal: NodeJS.Signals) {
const killPid = (pid: number, signal: NodeJS.Signals): void => {
try {
process.kill(pid, signal);
} catch (err) {
const e = err as NodeJS.ErrnoException;
if (e.code !== "ESRCH") throw err;
if ((err as NodeJS.ErrnoException).code !== "ESRCH") throw err;
}
}
};

function buildProcessTree(
/**
* The tree's pids in kill order: a post-order walk from the root, so children are
* always killed before their parents (descending pid order only does that when
* pids never wrapped around).
*/
const killOrder = (tree: ProcessTree, root: number): number[] => {
const order: number[] = [];
const seen = new Set<number>();
const visit = (current: number): void => {
if (seen.has(current)) return;
seen.add(current);
for (const child of tree[current] ?? []) visit(child);
order.push(current);
};
visit(root);
for (const key of Object.keys(tree)) {
const pid = Number(key);
if (!seen.has(pid)) {
seen.add(pid);
order.push(pid);
}
}
return order;
};

const killAll = (tree: ProcessTree, root: number, signal: NodeJS.Signals): void => {
for (const pid of killOrder(tree, root)) killPid(pid, signal);
};

const buildProcessTree = (
parentPid: number,
tree: { [key: number]: number[] },
tree: ProcessTree,
pidsToProcess: { [key: number]: number },
helpers: Set<number>,
spawnChildProcessesList: (parentPid: string) => ChildProcessWithoutNullStreams,
cb: () => void,
) {
): void => {
const ps = spawnChildProcessesList(parentPid.toString());
// The listing helpers are children of this process: when the root is this process
// (the signal handler kills its own tree) a helper would list itself as a child.
if (ps.pid !== undefined) helpers.add(ps.pid);
let allData = "";
ps.stdout.on("data", function (data) {
ps.stdout.on("data", (data: Buffer) => {
allData += data.toString("ascii");
});

const onClose = function (code: number | null) {
ps.on("close", (code: number | null) => {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete pidsToProcess[parentPid];

if (code != 0) {
if (Object.keys(pidsToProcess).length == 0) {
cb();
}
if (code !== 0) {
if (Object.keys(pidsToProcess).length === 0) cb();
return;
}

if (allData)
allData.match(/\d+/g)?.forEach(function (pid: string) {
const intPid = Number(pid);
if (tree[parentPid] === undefined) {
tree[parentPid] = [];
}
allData.match(/\d+/g)?.forEach((childPid: string) => {
const intPid = Number(childPid);
if (helpers.has(intPid)) return;
if (tree[parentPid] === undefined) tree[parentPid] = [];
tree[parentPid].push(intPid);
tree[intPid] = [];
pidsToProcess[intPid] = 1;
buildProcessTree(intPid, tree, pidsToProcess, spawnChildProcessesList, cb);
buildProcessTree(intPid, tree, pidsToProcess, helpers, spawnChildProcessesList, cb);
});
};
if (Object.keys(pidsToProcess).length === 0) cb();
});
};

ps.on("close", onClose);
}
export const treeKill = (pid: number, signal: NodeJS.Signals): Promise<void> =>
new Promise((resolve) => {
if (process.platform === "win32") {
// taskkill throws when the process is already gone; treeKill runs from a
// signal handler, where a throw would surface as an unhandled rejection.
try {
execSync(`taskkill /pid ${pid} /T /F`);
} catch {
// The process tree is already dead: nothing left to kill.
}
resolve();
return;
}

const tree: ProcessTree = { [pid]: [] };
const listChildren =
process.platform === "darwin"
? (parentPid: string) => spawn("pgrep", ["-P", parentPid])
: (parentPid: string) => spawn("ps", ["-o", "pid", "--no-headers", "--ppid", parentPid]);
buildProcessTree(pid, tree, { [pid]: 1 }, new Set(), listChildren, () => {
killAll(tree, pid, signal);
resolve();
});
});
Loading