Add `killDescendants` option to also terminate descendant processes (#1256)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by GitHub · parent ade74bf · Browse files · 9 files·+209 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+209 added−4 removed
- tests:+90 added−0 removed
- other:+119 added−4 removed
Provenance
- Commit
84fa0ec- Tree
7dafbec- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
ade74bf
9 files changed+209 added−4 removed
modified:docs/api.md+15 added
1166 unmodified lines1167 Kill the subprocess when the current process exits.1168 1169 [More info.](termination.md#current-process-exit)1170 1171+### options.killDescendants1172+1173+_Type:_ `boolean`\1174+_Default:_ `false`1175+1176+When the subprocess is terminated by Execa, also terminate all of its descendant processes, instead of only the subprocess itself.1177+1178+This is useful when the subprocess spawns its own processes, such as when using the [`shell`](#optionsshell) option.1179+1180+On Unix, this spawns the subprocess in its own [process group](https://en.wikipedia.org/wiki/Process_group). On Windows, this uses [`taskkill`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill).1181+1182+This is best-effort: descendant processes that create their own process group or session are not terminated.1183+1184+[More info.](termination.md#killing-descendant-processes)1185+1186 ### options.uid1187 1188 _Type:_ `number`\1189 _Default:_ current user identifier172 unmodified linesmodified:docs/termination.md+20 added-1 removed
190 unmodified lines191 - The [`cleanup`](api.md#optionscleanup) option is `false`.192 - The subprocess is run in the background using the [`detached`](api.md#optionsdetached) option.193 - The current process was terminated abruptly, for example, with [`SIGKILL`](#sigkill) as opposed to [`SIGTERM`](#sigterm) or a successful exit.194 195-On Windows, only the subprocess is terminated, not the other processes it might have spawned. To also terminate those, the [`windowsHide: false`](windows.md#console-window) option can be used.195+By default, only the subprocess is terminated, not the other processes it might have spawned. The [`killDescendants`](#killing-descendant-processes) option can be used to also terminate those.196 197+## Killing descendant processes198+199+By default, [terminating](#signal-termination) a subprocess only sends a signal to that subprocess, not to any process it might have spawned itself. For example, terminating a subprocess started with the [`shell`](api.md#optionsshell) option only terminates the shell, not the command it is running.200+201+The [`killDescendants`](api.md#optionskilldescendants) option terminates the whole process tree instead: the subprocess and all of its descendants. This applies to every way Execa terminates a subprocess, including [`subprocess.kill()`](#signal-termination), the [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) and [`cleanup`](#current-process-exit) options, and the [`forceKillAfterDelay`](#forceful-termination) escalation.202+203+```js204+// Without `killDescendants`, only the shell is terminated, and `sleep` keeps running205+const subprocess = execa({shell: true, killDescendants: true})`sleep 60`;206+subprocess.kill();207+await subprocess;208+```209+210+On Unix, this spawns the subprocess in its own [process group](https://en.wikipedia.org/wiki/Process_group), then sends the signal to that group. On Windows, this uses [`taskkill`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill), which terminates the process tree tracked by the OS.211+212+This is best-effort. On Unix, descendant processes that create their own process group or session (for example, daemons calling [`setsid()`](https://man7.org/linux/man-pages/man2/setsid.2.html)) escape termination. On Unix, because the subprocess runs in its own process group, it is also detached from the terminal, so pressing `CTRL-C` no longer forwards [`SIGINT`](#sigint) to it.213+214+This option cannot be used with [synchronous methods](execution.md#synchronous-execution).215+216 ## Signal termination217 218 [`subprocess.kill()`](api.md#subprocesskillsignal-error) sends a [signal](https://en.wikipedia.org/wiki/Signal_(IPC)) to the subprocess. This is an inter-process message handled by the OS. Most (but [not all](https://github.com/ehmicky/human-signals#action)) signals terminate the subprocess.219 160 unmodified linesmodified:lib/arguments/options.js+2 added
52 unmodified lines53545556575859606111 unmodified lines73747576777879808121 unmodified lines52 unmodified lines localDir: localDirectory = cwd, encoding = 'utf8', reject = true, cleanup = true, killDescendants = false, all = false, windowsHide = true, killSignal = 'SIGTERM', forceKillAfterDelay = true,11 unmodified lines localDirectory, encoding, reject, cleanup, killDescendants, all, windowsHide, killSignal, forceKillAfterDelay,21 unmodified linesmodified:lib/methods/main-async.js+3 added-2 removed
12 unmodified lines13 import {handleStdioAsync} from '../stdio/handle-async.js';14 import {stripNewline} from '../io/strip-newline.js';15 import {pipeOutputAsync} from '../io/output-async.js';16 import {subprocessKill} from '../terminate/kill.js';17+import {getSpawnOptions, getKillFunction} from '../terminate/kill-descendants.js';18 import {cleanupOnExit} from '../terminate/cleanup.js';19 import {pipeToSubprocess} from '../pipe/setup.js';20 import {makeAllStream} from '../resolve/all-async.js';21 import {waitForSubprocessResult} from '../resolve/wait-subprocess.js';62 unmodified lines84 85 const spawnSubprocessAsync = ({file, commandArguments, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors}) => {86 let subprocess;87 try {87- subprocess = spawn(...concatenateShell(file, commandArguments, options));88+ subprocess = spawn(...concatenateShell(file, commandArguments, getSpawnOptions(options)));89 } catch (error) {90 return handleEarlyError({91 error,92 command,14 unmodified lines107 108 const context = {};109 const onInternalError = createDeferred();110 const kill = subprocessKill.bind(undefined, {110- kill: subprocess.kill.bind(subprocess),111+ kill: getKillFunction(subprocess, options),112 options,113 onInternalError,114 context,115 controller,120 unmodified linesmodified:lib/methods/main-sync.js+5 added-1 removed
49 unmodified lines50 // Options normalization logic specific to sync methods51 const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;52 53 // Options validation logic specific to sync methods54-const validateSyncOptions = ({ipc, ipcInput, detached, cancelSignal}) => {54+const validateSyncOptions = ({ipc, ipcInput, detached, cancelSignal, killDescendants}) => {55 if (ipcInput) {56 throwInvalidSyncOption('ipcInput');57 }58 4 unmodified lines63 if (detached) {64 throwInvalidSyncOption('detached: true');65 }66 67+ if (killDescendants) {68+ throwInvalidSyncOption('killDescendants: true');69+ }70+71 if (cancelSignal) {72 throwInvalidSyncOption('cancelSignal');73 }74 };93 unmodified linesadded:lib/terminate/kill-descendants.js+54 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import process from 'node:process';import {execFile} from 'node:child_process';
const isWindows = process.platform === 'win32';
// The `killDescendants` option terminates the whole process tree, not just the direct child.// On Unix, this requires spawning the subprocess in its own process group, so we override the// `detached` argument passed to `child_process.spawn()`.// This is kept separate from the user-facing `detached` option, which must keep its own value,// so the `cleanup` behavior is not affected.export const getSpawnOptions = options => options.killDescendants && !isWindows ? {...options, detached: true} : options;
// Returns the low-level function used to send a signal to the subprocess.// With the `killDescendants` option, the signal is sent to the whole process tree.export const getKillFunction = (subprocess, {killDescendants}) => { if (!killDescendants) { return subprocess.kill.bind(subprocess); }
const killDescendantsFunction = isWindows ? killDescendantsWindows : killDescendantsUnix; return killDescendantsFunction.bind(undefined, subprocess);};
// On Unix, the subprocess is its own process group leader (its PGID equals its PID), since it// was spawned with `detached: true`. Sending the signal to `-pid` targets the whole group.const killDescendantsUnix = (subprocess, signal) => { if (subprocess.pid === undefined) { return false; }
try { return process.kill(-subprocess.pid, signal); } catch { // The process group might already be gone, or signaling it might not be permitted, so we // fall back to the direct child. Like `ChildProcess.kill()`, this returns `false` instead of throwing. return subprocess.kill(signal); }};
// Windows has no process groups. Instead, `taskkill /T` recursively terminates the process tree.// It must run while the tree is still intact, so it is the only termination performed: killing the// direct subprocess first would orphan its descendants before `taskkill` could enumerate them.// Windows does not support signals, so the signal argument is ignored (`/F` terminates the tree).const killDescendantsWindows = subprocess => { if (subprocess.pid === undefined) { return false; }
// This is best-effort: any error (such as the subprocess having already exited) is ignored. execFile('taskkill', ['/pid', `${subprocess.pid}`, '/T', '/F'], () => {}); return true;};added:test/terminate/kill-descendants.js+90 added
1+import process from 'node:process';2+import {setTimeout} from 'node:timers/promises';3+import test from 'ava';4+import isRunning from 'is-running';5+import {execa, execaSync} from '../../index.js';6+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7+8+setFixtureDirectory();9+10+const isWindows = process.platform === 'win32';11+12+const pollForSubprocessExit = async pid => {13+ while (isRunning(pid)) {14+ // eslint-disable-next-line no-await-in-loop15+ await setTimeout(100);16+ }17+};18+19+// `ipc-send-pid.js` spawns a descendant process (`forever.js`) and sends back its PID.20+const spawnDescendant = async (killDescendants, options) => {21+ const subprocess = execa('ipc-send-pid.js', ['false', 'false'], {22+ stdio: 'ignore',23+ ipc: true,24+ killDescendants,25+ ...options,26+ });27+ const descendantPid = await subprocess.getOneMessage();28+ return {subprocess, descendantPid};29+};30+31+test('killDescendants terminates descendant processes', async t => {32+ const {subprocess, descendantPid} = await spawnDescendant(true);33+ t.true(isRunning(descendantPid));34+35+ subprocess.kill();36+ await t.throwsAsync(subprocess);37+ t.false(isRunning(subprocess.pid));38+39+ await Promise.race([40+ setTimeout(1e4, undefined, {ref: false}),41+ pollForSubprocessExit(descendantPid),42+ ]);43+ t.false(isRunning(descendantPid));44+});45+46+test('killDescendants also terminates descendant processes when the subprocess times out', async t => {47+ const {subprocess, descendantPid} = await spawnDescendant(true, {timeout: 1000});48+ t.true(isRunning(descendantPid));49+50+ const {timedOut} = await t.throwsAsync(subprocess);51+ t.true(timedOut);52+53+ await Promise.race([54+ setTimeout(1e4, undefined, {ref: false}),55+ pollForSubprocessExit(descendantPid),56+ ]);57+ t.false(isRunning(descendantPid));58+});59+60+// On Windows, terminating the direct subprocess already terminates its descendants, so this61+// only asserts the default Unix behavior of leaving descendants running.62+if (!isWindows) {63+ test('descendant processes are not terminated without killDescendants', async t => {64+ const {subprocess, descendantPid} = await spawnDescendant(false);65+ t.true(isRunning(descendantPid));66+67+ subprocess.kill();68+ await t.throwsAsync(subprocess);69+ t.false(isRunning(subprocess.pid));70+71+ t.true(isRunning(descendantPid));72+ process.kill(descendantPid, 'SIGKILL');73+ });74+75+ test('timeout does not terminate descendants without killDescendants', async t => {76+ const {subprocess, descendantPid} = await spawnDescendant(false, {timeout: 1000});77+ t.true(isRunning(descendantPid));78+79+ const {timedOut} = await t.throwsAsync(subprocess);80+ t.true(timedOut);81+ t.true(isRunning(descendantPid));82+ process.kill(descendantPid, 'SIGKILL');83+ });84+}85+86+test('Cannot use "killDescendants" option, sync', t => {87+ t.throws(() => {88+ execaSync('empty.js', {killDescendants: true});89+ }, {message: /The "killDescendants: true" option cannot be used/});90+});modified:test-d/arguments/options.test-d.ts+7 added
273 unmodified lines274 expectError(execaSync('unicorns', {detached: true as boolean}));275 expectError(await execa('unicorns', {detached: 'true'}));276 expectError(execaSync('unicorns', {detached: 'true'}));277 278+await execa('unicorns', {killDescendants: true});279+expectError(execaSync('unicorns', {killDescendants: true}));280+await execa('unicorns', {killDescendants: true as boolean});281+expectError(execaSync('unicorns', {killDescendants: true as boolean}));282+expectError(await execa('unicorns', {killDescendants: 'true'}));283+expectError(execaSync('unicorns', {killDescendants: 'true'}));284+285 await execa('unicorns', {cancelSignal: AbortSignal.abort()});286 expectError(execaSync('unicorns', {cancelSignal: AbortSignal.abort()}));287 expectError(await execa('unicorns', {cancelSignal: false}));288 expectError(execaSync('unicorns', {cancelSignal: false}));7 unmodified linesmodified:types/arguments/options.d.ts+13 added
328 unmodified lines329 */330 readonly cleanup?: Unless<IsSync, boolean>;331 332 /**333+ When the subprocess is terminated by Execa, also terminate all of its descendant processes, instead of only the subprocess itself.334+335+ This is useful when the subprocess spawns its own processes, such as when using the `shell` option.336+337+ On Unix, this spawns the subprocess in its own [process group](https://en.wikipedia.org/wiki/Process_group). On Windows, this uses [`taskkill`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill).338+339+ This is best-effort: descendant processes that create their own process group or session are not terminated.340+341+ @default false342+ */343+ readonly killDescendants?: Unless<IsSync, boolean>;344+345+ /**346 Sets the [user identifier](https://en.wikipedia.org/wiki/User_identifier) of the subprocess.347 348 @default current user identifier349 */76 unmodified lines