Skip to content
Myr

kill-descendants.js

This file

Path

lib/terminate/kill-descendants.js

95 lines · 4.8 KiB · JavaScript

Last changed by

TweaksSindre Sorhusbefore adoption698a1b8

History of this file

Take it

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

lines 1–2why, one step back
1import process from 'node:process';
2import {execFile} from 'node:child_process';

Improve `taskkill` usage (#1258)Sindre Sorhusbefore adoption3d9d820

line 3why, one step back
3import path from 'node:path/win32';

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

lines 4–11why, one step back
4
5const isWindows = process.platform === 'win32';67// The `killDescendants` option terminates the whole process tree, not just the direct child.8// On Unix, this requires spawning the subprocess in its own process group, so we override the9// `detached` argument passed to `child_process.spawn()`.10// This is kept separate from the user-facing `detached` option, which must keep its own value,11// so the `cleanup` behavior is not affected.

TweaksSindre Sorhusbefore adoption698a1b8

line 12why, one step back
12export const getSpawnOptions = options => !isWindows && options.killDescendants

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

lines 13–17why, one step back
13 ? {...options, detached: true}
14 : options;1516// Returns the low-level function used to send a signal to the subprocess.17// With the `killDescendants` option, the signal is sent to the whole process tree.

TweaksSindre Sorhusbefore adoption698a1b8

line 18why, one step back
18export const getKillFunction = (subprocess, {killDescendants}) => {

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

line 19why, one step back
19 if (!killDescendants) {

TweaksSindre Sorhusbefore adoption698a1b8

lines 20–24why, one step back
20 /*
21 `subprocess.pid` is `undefined` when the subprocess failed to spawn, e.g. with `ENOENT`.22 `ChildProcess.prototype.kill()` then signals the current process group, since its process id is `0`.23 So, like `ChildProcess.prototype.kill()` does for a subprocess which already exited, nothing is signaled and `false` is returned.24 */

Fix a subprocess which failed to spawn signaling the current process and never ending its streamsSindre Sorhusbefore adoption5464d43

lines 25–26why, one step back
25 const killSubprocess = subprocess.kill.bind(subprocess);
26 return (...arguments_) => (subprocess.pid === undefined ? false : killSubprocess(...arguments_));

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

lines 27–29why, one step back
27 }
2829 const killDescendantsFunction = isWindows ? killDescendantsWindows : killDescendantsUnix;

TweaksSindre Sorhusbefore adoption698a1b8

line 30why, one step back
30 return killDescendantsFunction.bind(undefined, subprocess);

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

lines 31–32why, one step back
31};
32

Fix `killDescendants` signaling unrelated processes once Execa is done with the subprocessSindre Sorhusbefore adoption9c5c71c

line 33why, one step back
33/*

TweaksSindre Sorhusbefore adoption698a1b8

lines 34–35why, one step back
34Unlike `subprocess.kill()`, signaling a process group or a process tree uses the PID directly, without going through the subprocess' handle. The OS can re-assign that PID once it is not used anymore, and signaling it then would terminate an unrelated process, and on Windows its own descendants too.
35On Unix, a PID stays reserved as long as it is the process group ID of a running process, i.e. as long as any descendant in that group is still running. So signaling the process group after the subprocess exited is still useful, e.g. for the `forceKillAfterDelay` escalation while Execa is waiting on a descendant, or with `subprocess.kill()` to terminate background descendants once the subprocess has settled. Once the whole group exited, the PID can only be signaled if the OS re-assigned it to a new process group leader, which is unlikely, so this is a documented limitation.

Fix `killDescendants` signaling unrelated processes once Execa is done with the subprocessSindre Sorhusbefore adoption9c5c71c

lines 36–37why, one step back
36On Windows, there are no process groups: a PID is only reserved while a handle to the process is open, which Node.js closes once the subprocess exits. `taskkill /T` also cannot find the descendants of a process which exited. So the process tree is never signaled once the subprocess exited.
37*/

TweaksSindre Sorhusbefore adoption698a1b8

lines 38–39why, one step back
38const isAbandoned = subprocess => subprocess.pid === undefined
39 || (isWindows && hasExited(subprocess));

Fix `killDescendants` signaling unrelated processes once Execa is done with the subprocessSindre Sorhusbefore adoption9c5c71c

lines 40–42why, one step back
40
41const hasExited = ({exitCode, signalCode}) => exitCode !== null || signalCode !== null;42

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

lines 43–44why, one step back
43// On Unix, the subprocess is its own process group leader (its PGID equals its PID), since it
44// was spawned with `detached: true`. Sending the signal to `-pid` targets the whole group.

TweaksSindre Sorhusbefore adoption698a1b8

lines 45–46why, one step back
45const killDescendantsUnix = (subprocess, signal) => {
46 if (isAbandoned(subprocess)) {

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

lines 47–59why, one step back
47 return false;
48 }4950 try {51 return process.kill(-subprocess.pid, signal);52 } catch {53 // The process group might already be gone, or signaling it might not be permitted, so we54 // fall back to the direct child. Like `ChildProcess.kill()`, this returns `false` instead of throwing.55 return subprocess.kill(signal);56 }57};5859// Windows has no process groups. Instead, `taskkill /T` recursively terminates the process tree.

Improve `taskkill` usage (#1258)Sindre Sorhusbefore adoption3d9d820

lines 60–63why, one step back
60// It must run while the tree is still intact, so direct subprocess termination is only used as a
61// fallback: killing the direct subprocess first would orphan its descendants before `taskkill` could enumerate them.62// If `taskkill` is unavailable or fails, the fallback only terminates the direct subprocess.63// `taskkill` ignores the signal (`/F` terminates the tree).

TweaksSindre Sorhusbefore adoption698a1b8

lines 64–65why, one step back
64const killDescendantsWindows = (subprocess, signal) => {
65 if (isAbandoned(subprocess)) {

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

lines 66–68why, one step back
66 return false;
67 }68

Improve `taskkill` usage (#1258)Sindre Sorhusbefore adoption3d9d820

lines 69–79why, one step back
69 const taskkillFile = getTaskkillFile();
70 if (taskkillFile === undefined) {71 return subprocess.kill(signal);72 }7374 // This is best-effort: if `taskkill` fails, still try the direct subprocess.75 execFile(taskkillFile, ['/pid', `${subprocess.pid}`, '/T', '/F'], error => {76 if (error) {77 subprocess.kill(signal);78 }79 });

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

line 80why, one step back
80 return true;

Improve `taskkill` usage (#1258)Sindre Sorhusbefore adoption3d9d820

lines 81–94why, one step back
81};
8283export const getTaskkillFile = () => {84 const windowsDirectory = [process.env.SystemRoot, process.env.windir]85 .find(directory => directory && isWindowsDriveAbsolutePath(directory));8687 return windowsDirectory === undefined88 ? undefined89 : path.join(windowsDirectory, 'System32', 'taskkill.exe');90};9192const isWindowsDriveAbsolutePath = directory => {93 const {root} = path.parse(directory);94 return /^[a-z]:[/\\]/i.test(root);

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

line 95why, one step back
95};