- Extract shared Windows command/process utilities - Add process tree kill and probe process wrappers - Cover output truncation and Windows command behavior with tests
33 lines
995 B
TypeScript
33 lines
995 B
TypeScript
import { spawnSync, type ChildProcess as NodeChildProcess } from "node:child_process";
|
|
|
|
type KillableChildProcess = Pick<NodeChildProcess, "kill" | "pid">;
|
|
|
|
interface KillChildProcessTreeOptions {
|
|
readonly platform?: NodeJS.Platform;
|
|
readonly spawnSyncImpl?: typeof spawnSync;
|
|
}
|
|
|
|
/**
|
|
* On Windows with shell-backed processes, direct kill only terminates the
|
|
* wrapper process. Use `taskkill /T` first so the spawned process tree exits.
|
|
*/
|
|
export function killChildProcessTree(
|
|
child: KillableChildProcess,
|
|
signal: NodeJS.Signals = "SIGTERM",
|
|
options: KillChildProcessTreeOptions = {},
|
|
): void {
|
|
const platform = options.platform ?? process.platform;
|
|
if (platform === "win32" && child.pid !== undefined) {
|
|
try {
|
|
(options.spawnSyncImpl ?? spawnSync)("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
stdio: "ignore",
|
|
});
|
|
return;
|
|
} catch {
|
|
// Fall through to direct kill when taskkill is unavailable.
|
|
}
|
|
}
|
|
|
|
child.kill(signal);
|
|
}
|