Skip to content
Myr

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

9 files+209 added−4 removed

modified:docs/api.md+15 added
1166 unmodified lines
1167Kill the subprocess when the current process exits.11681169[More info.](termination.md#current-process-exit)11701171### options.killDescendants11721173_Type:_ `boolean`\1174_Default:_ `false`11751176When the subprocess is terminated by Execa, also terminate all of its descendant processes, instead of only the subprocess itself.11771178This is useful when the subprocess spawns its own processes, such as when using the [`shell`](#optionsshell) option.11791180On 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).11811182This is best-effort: descendant processes that create their own process group or session are not terminated.11831184[More info.](termination.md#killing-descendant-processes)11851186### options.uid11871188_Type:_ `number`\1189_Default:_ current user identifier
172 unmodified lines
modified:docs/termination.md+20 added-1 removed
190 unmodified lines
191- 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.194195On 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.195By 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.196197## Killing descendant processes198199By 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.200201The [`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.202203```js204// Without `killDescendants`, only the shell is terminated, and `sleep` keeps running205const subprocess = execa({shell: true, killDescendants: true})`sleep 60`;206subprocess.kill();207await subprocess;208```209210On 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.211212This 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.213214This option cannot be used with [synchronous methods](execution.md#synchronous-execution).215216## Signal termination217218[`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 lines
modified:lib/arguments/options.js+2 added
modified:lib/methods/main-async.js+3 added-2 removed
12 unmodified lines
13import {handleStdioAsync} from '../stdio/handle-async.js';14import {stripNewline} from '../io/strip-newline.js';15import {pipeOutputAsync} from '../io/output-async.js';16import {subprocessKill} from '../terminate/kill.js';17import {getSpawnOptions, getKillFunction} from '../terminate/kill-descendants.js';18import {cleanupOnExit} from '../terminate/cleanup.js';19import {pipeToSubprocess} from '../pipe/setup.js';20import {makeAllStream} from '../resolve/all-async.js';21import {waitForSubprocessResult} from '../resolve/wait-subprocess.js';
62 unmodified lines
8485const 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 lines
107108 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 lines
modified:lib/methods/main-sync.js+5 added-1 removed
49 unmodified lines
50// Options normalization logic specific to sync methods51const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;5253// Options validation logic specific to sync methods54const validateSyncOptions = ({ipc, ipcInput, detached, cancelSignal}) => {54const validateSyncOptions = ({ipc, ipcInput, detached, cancelSignal, killDescendants}) => {55 if (ipcInput) {56 throwInvalidSyncOption('ipcInput');57 }58
4 unmodified lines
63 if (detached) {64 throwInvalidSyncOption('detached: true');65 }6667 if (killDescendants) {68 throwInvalidSyncOption('killDescendants: true');69 }7071 if (cancelSignal) {72 throwInvalidSyncOption('cancelSignal');73 }74};
93 unmodified lines
added:lib/terminate/kill-descendants.js+54 added
added:test/terminate/kill-descendants.js+90 added
1import process from 'node:process';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import isRunning from 'is-running';5import {execa, execaSync} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';78setFixtureDirectory();910const isWindows = process.platform === 'win32';1112const pollForSubprocessExit = async pid => {13 while (isRunning(pid)) {14 // eslint-disable-next-line no-await-in-loop15 await setTimeout(100);16 }17};1819// `ipc-send-pid.js` spawns a descendant process (`forever.js`) and sends back its PID.20const 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};3031test('killDescendants terminates descendant processes', async t => {32 const {subprocess, descendantPid} = await spawnDescendant(true);33 t.true(isRunning(descendantPid));3435 subprocess.kill();36 await t.throwsAsync(subprocess);37 t.false(isRunning(subprocess.pid));3839 await Promise.race([40 setTimeout(1e4, undefined, {ref: false}),41 pollForSubprocessExit(descendantPid),42 ]);43 t.false(isRunning(descendantPid));44});4546test('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));4950 const {timedOut} = await t.throwsAsync(subprocess);51 t.true(timedOut);5253 await Promise.race([54 setTimeout(1e4, undefined, {ref: false}),55 pollForSubprocessExit(descendantPid),56 ]);57 t.false(isRunning(descendantPid));58});5960// On Windows, terminating the direct subprocess already terminates its descendants, so this61// only asserts the default Unix behavior of leaving descendants running.62if (!isWindows) {63 test('descendant processes are not terminated without killDescendants', async t => {64 const {subprocess, descendantPid} = await spawnDescendant(false);65 t.true(isRunning(descendantPid));6667 subprocess.kill();68 await t.throwsAsync(subprocess);69 t.false(isRunning(subprocess.pid));7071 t.true(isRunning(descendantPid));72 process.kill(descendantPid, 'SIGKILL');73 });7475 test('timeout does not terminate descendants without killDescendants', async t => {76 const {subprocess, descendantPid} = await spawnDescendant(false, {timeout: 1000});77 t.true(isRunning(descendantPid));7879 const {timedOut} = await t.throwsAsync(subprocess);80 t.true(timedOut);81 t.true(isRunning(descendantPid));82 process.kill(descendantPid, 'SIGKILL');83 });84}8586test('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 lines
274expectError(execaSync('unicorns', {detached: true as boolean}));275expectError(await execa('unicorns', {detached: 'true'}));276expectError(execaSync('unicorns', {detached: 'true'}));277278await execa('unicorns', {killDescendants: true});279expectError(execaSync('unicorns', {killDescendants: true}));280await execa('unicorns', {killDescendants: true as boolean});281expectError(execaSync('unicorns', {killDescendants: true as boolean}));282expectError(await execa('unicorns', {killDescendants: 'true'}));283expectError(execaSync('unicorns', {killDescendants: 'true'}));284285await execa('unicorns', {cancelSignal: AbortSignal.abort()});286expectError(execaSync('unicorns', {cancelSignal: AbortSignal.abort()}));287expectError(await execa('unicorns', {cancelSignal: false}));288expectError(execaSync('unicorns', {cancelSignal: false}));
7 unmodified lines
modified:types/arguments/options.d.ts+13 added
328 unmodified lines
329 */330 readonly cleanup?: Unless<IsSync, boolean>;331332 /**333 When the subprocess is terminated by Execa, also terminate all of its descendant processes, instead of only the subprocess itself.334335 This is useful when the subprocess spawns its own processes, such as when using the `shell` option.336337 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).338339 This is best-effort: descendant processes that create their own process group or session are not terminated.340341 @default false342 */343 readonly killDescendants?: Unless<IsSync, boolean>;344345 /**346 Sets the [user identifier](https://en.wikipedia.org/wiki/User_identifier) of the subprocess.347348 @default current user identifier349 */
76 unmodified lines