Skip to content
Myr

Fix `killDescendants` signaling unrelated processes once Execa is done with the subprocess

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 91d9ded · Browse files · 7 files+192 added−48 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+192 added−48 removed

  • tests:+172 added−38 removed
  • other:+20 added−10 removed

7 files+192 added−48 removed

modified:docs/api.md+1 added-1 removed
1181 unmodified lines
1182This is useful when the subprocess spawns its own processes, such as when using the [`shell`](#optionsshell) option.11831184On 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).11851186This is best-effort: descendant processes that create their own process group or session are not terminated.1186This is best-effort: descendant processes that create their own process group or session are not terminated. Also, descendants are not terminated once Execa is done with the subprocess, or on Windows once the subprocess exited, since its PID might then belong to an unrelated process.11871188[More info.](termination.md#killing-descendant-processes)11891190### options.uid
175 unmodified lines
modified:docs/termination.md+1 added-1 removed
207 unmodified lines
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.212This 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. Finally, the OS can re-assign the subprocess' PID to an unrelated process once it exited. So, descendants are not signaled anymore once Execa is done with the subprocess, i.e. once its promise has settled. On Windows, this applies as soon as the subprocess exited, which also prevents the [`forceKillAfterDelay`](#forceful-termination) escalation from terminating its descendants.213214This option cannot be used with [synchronous methods](execution.md#synchronous-execution).215216## Signal termination
163 unmodified lines
modified:lib/methods/main-async.js+1 added-1 removed
107 unmodified lines
108109 const context = {};110 const onInternalError = createDeferred();111 const kill = subprocessKill.bind(undefined, {112 kill: getKillFunction(subprocess, options),112 kill: getKillFunction(subprocess, options, controller),113 options,114 onInternalError,115 context,116 controller,
120 unmodified lines
modified:lib/terminate/kill-descendants.js+16 added-6 removed
added:test/fixtures/ipc-send-pid-stubborn.js+14 added
modified:test/terminate/kill-descendants.js+158 added-38 removed
85 unmodified lines
86 process.kill(descendantPid, 'SIGKILL');87 });88}8990/*91The `forceKillAfterDelay` escalation happens after the subprocess exited, since that is when its termination has been noticed.92A descendant which ignores `SIGTERM` is still running then, so the escalation must still reach it.93Otherwise, since that descendant keeps the subprocess' `stdout` open, awaiting the subprocess would never settle.94*/95test('killDescendants escalates to descendants which outlive the subprocess', async t => {96 const subprocess = execa('ipc-send-pid-stubborn.js', {97 ipc: true,98 killDescendants: true,99 forceKillAfterDelay: 1000,100 });101 const descendantPid = await subprocess.getOneMessage();102 t.true(isRunning(descendantPid));103104 subprocess.kill();105 const settled = await Promise.race([106 t.throwsAsync(subprocess).then(() => 'settled'),107 setTimeout(1e4, 'pending', {ref: false}),108 ]);109 t.is(settled, 'settled');110 t.false(isRunning(descendantPid));111});112113if (!isWindows) {114 // A PID can be re-assigned to an unrelated process once Execa is done with the subprocess, so its process group must not be signaled anymore115 const testAbandonedProcessGroup = test.macro(async (t, getSubprocess) => {116 const subprocess = getSubprocess();117 await t.throwsAsync(subprocess);118119 const originalKill = process.kill;120 t.teardown(() => {121 process.kill = originalKill;122 });123124 const signaledProcesses = [];125 process.kill = (pid, signal) => {126 signaledProcesses.push([pid, signal]);127 return true;128 };129130 t.false(subprocess.kill('SIGKILL'));131 t.deepEqual(signaledProcesses, []);132 });133134 test.serial('killDescendants does not signal the process group once Execa is done with the subprocess', testAbandonedProcessGroup, () => execa('fail.js', {killDescendants: true}));135136 test.serial('killDescendants does not signal the process group once Execa is done with a terminated subprocess', testAbandonedProcessGroup, () => {137 const subprocess = execa('forever.js', {killDescendants: true});138 subprocess.kill('SIGTERM');139 return subprocess;140 });141142 // While Execa is still waiting on the subprocess, its process group is still its own143 test.serial('killDescendants signals the process group while Execa is not done with the subprocess', async t => {144 const subprocess = execa('forever.js', {killDescendants: true});145146 const originalKill = process.kill;147 t.teardown(() => {148 process.kill = originalKill;149 });150151 const signaledProcesses = [];152 process.kill = (pid, signal) => {153 signaledProcesses.push([pid, signal]);154 return originalKill(pid, signal);155 };156157 t.true(subprocess.kill('SIGTERM'));158 t.deepEqual(signaledProcesses, [[-subprocess.pid, 'SIGTERM']]);159 process.kill = originalKill;160 await t.throwsAsync(subprocess);161 });162}163164test('Cannot use "killDescendants" option, sync', t => {165 t.throws(() => {166 execaSync('empty.js', {killDescendants: true});167 }, {message: /The "killDescendants: true" option cannot be used/});
37 unmodified lines
205 delete process.env.windir;206 t.is(getTaskkillFile(), undefined);207});208135test.serial('taskkill fallback uses direct subprocess kill when Windows directory is unavailable', async t => {209/*210The `taskkill` logic only runs on Windows, so the platform, the Windows directory and `taskkill` itself are faked to test it on any OS.211`lib/terminate/kill-descendants.js` reads `process.platform` when it is loaded, so it must be re-imported once the platform has been faked.212*/213let fakeWindowsCount = 0;214215const fakeWindows = async (t, systemRoot, execFile = () => {}) => {216 const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');217 const originalExecFile = childProcess.execFile;218 const {SystemRoot, windir} = process.env;219 t.teardown(() => {220 Object.defineProperty(process, 'platform', platformDescriptor);221 childProcess.execFile = originalExecFile;222 syncBuiltinESMExports();223 restoreEnvironment('SystemRoot', SystemRoot);224 restoreEnvironment('windir', windir);225 });226227 Object.defineProperty(process, 'platform', {value: 'win32'});145 process.env.SystemRoot = 'Windows';228 process.env.SystemRoot = systemRoot;229 delete process.env.windir;230 childProcess.execFile = execFile;231 syncBuiltinESMExports();232148 const {getKillFunction} = await import(`../../lib/terminate/kill-descendants.js?taskkill-fallback=${Date.now()}`);149 let killedWith;233 fakeWindowsCount += 1;234 const {getKillFunction} = await import(`../../lib/terminate/kill-descendants.js?fake-windows=${fakeWindowsCount}`);235 return getKillFunction;236};237238// Mimics the `ChildProcess` properties used to send the signal and to detect whether the subprocess is still running239const createFakeSubprocess = ({exitCode = null, signalCode = null} = {}) => {240 const subprocess = {241 pid: 123,242 exitCode,243 signalCode,244 kill(signal) {153 killedWith = signal;245 subprocess.killedWith = signal;246 return true;247 },248 };249 return subprocess;250};251252const abortedController = () => {253 const controller = new AbortController();254 controller.abort();255 return controller;256};257258test.serial('taskkill fallback uses direct subprocess kill when Windows directory is unavailable', async t => {259 const getKillFunction = await fakeWindows(t, 'Windows');260 const subprocess = createFakeSubprocess();261158 const kill = getKillFunction(subprocess, {killDescendants: true});262 const kill = getKillFunction(subprocess, {killDescendants: true}, new AbortController());263 t.true(kill('SIGTERM'));160 t.is(killedWith, 'SIGTERM');264 t.is(subprocess.killedWith, 'SIGTERM');265});266267test.serial('taskkill fallback uses direct subprocess kill when taskkill cannot be spawned', async t => {164 const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');165 const originalExecFile = childProcess.execFile;166 const {SystemRoot, windir} = process.env;167 t.teardown(() => {168 Object.defineProperty(process, 'platform', platformDescriptor);169 childProcess.execFile = originalExecFile;170 syncBuiltinESMExports();171 restoreEnvironment('SystemRoot', SystemRoot);172 restoreEnvironment('windir', windir);173 });174175 Object.defineProperty(process, 'platform', {value: 'win32'});176 process.env.SystemRoot = 'C:\\MissingWindows';177 delete process.env.windir;178268 const taskkillFailure = Promise.withResolvers();180 childProcess.execFile = (file, arguments_, callback) => {269 const getKillFunction = await fakeWindows(t, 'C:\\MissingWindows', (file, arguments_, callback) => {270 t.is(file, path.join('C:\\MissingWindows', 'System32', 'taskkill.exe'));271 t.deepEqual(arguments_, ['/pid', '123', '/T', '/F']);272 queueMicrotask(() => {273 callback(new Error('spawn failed'));274 taskkillFailure.resolve();275 });187 };276 });277 const subprocess = createFakeSubprocess();278189 syncBuiltinESMExports();279 const kill = getKillFunction(subprocess, {killDescendants: true}, new AbortController());280 t.true(kill('SIGTERM'));281 t.is(subprocess.killedWith, undefined);282191 const {getKillFunction} = await import(`../../lib/terminate/kill-descendants.js?taskkill-spawn-fallback=${Date.now()}`);192 let killedWith;193 const subprocess = {194 pid: 123,195 kill(signal) {196 killedWith = signal;197 return true;198 },199 };283 await taskkillFailure.promise;284 t.is(subprocess.killedWith, 'SIGTERM');285});286287// Once Execa is done with the subprocess, its PID can be re-assigned by the OS, so its process tree must not be terminated anymore288test.serial('taskkill is not spawned once Execa is done with the subprocess', async t => {289 let isTaskkillSpawned = false;290 const getKillFunction = await fakeWindows(t, 'C:\\Windows', () => {291 isTaskkillSpawned = true;292 });293 const subprocess = createFakeSubprocess({exitCode: 0});294201 const kill = getKillFunction(subprocess, {killDescendants: true});295 const kill = getKillFunction(subprocess, {killDescendants: true}, abortedController());296 t.false(kill('SIGTERM'));297 t.false(isTaskkillSpawned);298 t.is(subprocess.killedWith, undefined);299});300301// While Execa is still waiting on the subprocess, its process tree is still its own, even after it exited302test.serial('taskkill is still spawned after the subprocess exited', async t => {303 let taskkillArguments;304 const getKillFunction = await fakeWindows(t, 'C:\\Windows', (file, arguments_) => {305 taskkillArguments = arguments_;306 });307 const subprocess = createFakeSubprocess({exitCode: 0});308309 const kill = getKillFunction(subprocess, {killDescendants: true}, new AbortController());310 t.true(kill('SIGTERM'));203 t.is(killedWith, undefined);311 t.deepEqual(taskkillArguments, ['/pid', '123', '/T', '/F']);312});313205 await taskkillFailure.promise;206 t.is(killedWith, 'SIGTERM');314// A subprocess which never spawned has no PID to signal315test.serial('taskkill is not spawned when the subprocess has no PID', async t => {316 let isTaskkillSpawned = false;317 const getKillFunction = await fakeWindows(t, 'C:\\Windows', () => {318 isTaskkillSpawned = true;319 });320 const subprocess = createFakeSubprocess();321 subprocess.pid = undefined;322323 const kill = getKillFunction(subprocess, {killDescendants: true}, new AbortController());324 t.false(kill('SIGTERM'));325 t.false(isTaskkillSpawned);326 t.is(subprocess.killedWith, undefined);327});328329const restoreEnvironment = (name, value) => {330 if (value === undefined) {
5 unmodified lines
modified:types/arguments/options.d.ts+1 added-1 removed
338 unmodified lines
339 This is useful when the subprocess spawns its own processes, such as when using the `shell` option.340341 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).342343 This is best-effort: descendant processes that create their own process group or session are not terminated.343 This is best-effort: descendant processes that create their own process group or session are not terminated. Also, descendants are not terminated once Execa is done with the subprocess, or on Windows once the subprocess exited, since its PID might then belong to an unrelated process.344345 @default false346 */347 readonly killDescendants?: Unless<IsSync, boolean>;
82 unmodified lines