Skip to content
Myr

Add feature to retry process killing after specified duration (#208)

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

authored by zokker13 · committed by Sindre Sorhus · parent fcd3d85 · Browse files · 6 files+153 added−1 removed
This commit

State

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

Trailers

  • Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>

Diff stats

6 files+153 added−1 removed

  • other:+153 added−1 removed

6 files+153 added−1 removed

added:fixtures/no-killable+12 added
1#!/usr/bin/env node2'use strict';34process.on('SIGTERM', () => {5 console.log('Received SIGTERM, but we ignore it');6});78process.send('');910setInterval(() => {11 // Run forever12}, 20000);
modified:index.d.ts+21 added
277 unmodified lines
278 */279 isCanceled: boolean;280 }281282 interface KillOptions {283 /**284 If the first signal does not terminate the child process after a specified timeout, a `SIGKILL` signal will be sent to the process.285286 @default true287 */288 forceKill?: boolean;289290 /**291 Milliseconds to wait for the child process to terminate before sending a `SIGKILL` signal.292293 @default 5000294 */295 forceKillAfter?: number;296 }297298 interface ExecaChildPromise<StdoutErrorType> {299 catch<ResultType = never>(300 onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>301 ): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;302303 /**304 Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.305 */306 kill(signal?: string, options?: execa.KillOptions): void;307308 /**309 Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.310 */311 cancel(): void;312 }
113 unmodified lines
modified:index.js+25 added
211 unmodified lines
212213 return [file, ...args].join(' ');214}215216function shouldForceKill(signal, options, killResult) {217 return ((typeof signal === 'string' &&218 signal.toUpperCase() === 'SIGTERM') ||219 signal === os.constants.signals.SIGTERM) &&220 options.forceKill !== false &&221 killResult;222}223224const execa = (file, args, options) => {225 const parsed = handleArgs(file, args, options);226 const {encoding, buffer, maxBuffer} = parsed.options;227 const joinedCommand = joinCommand(file, args);
10 unmodified lines
238 killed: false239 }));240 }241242 const originalKill = spawned.kill.bind(spawned);243 spawned.kill = (signal = 'SIGTERM', options = {}) => {244 const killResult = originalKill(signal);245 if (shouldForceKill(signal, options, killResult)) {246 const forceKillAfter = Number.isInteger(options.forceKillAfter) ?247 options.forceKillAfter :248 5000;249 setTimeout(() => {250 try {251 originalKill('SIGKILL');252 } catch (_) {}253 }, forceKillAfter).unref();254 }255256 return killResult;257 };258259 // #115260 let removeExitHandler;261 if (parsed.options.cleanup && !parsed.options.detached) {262 removeExitHandler = onExit(() => {
217 unmodified lines
modified:index.test-d.ts+8 added
modified:readme.md+26 added-1 removed
110 unmodified lines
111 killed: false112 }113 */114}115116// Kill a process with SIGTERM, and after 2 seconds, kill it with SIGKILL117const subprocess = execa('node');118setTimeout(() => {119 subprocess.kill('SIGTERM', {120 forceKillAfter: 2000121 });122}, 1000);123```124117125## API126127### execa(file, arguments, [options])128
6 unmodified lines
135Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) which:136 - is also a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).137 - exposes the following additional methods and properties.138139#### kill([signal], [options])140141Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal) except: if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.142143##### options.forceKill144145Type: `boolean`<br>146Default: `true`147148If the first signal does not terminate the child process after a specified timeout, a `SIGKILL` signal will be sent to the process.149150##### options.forceKillAfter151152Type: `string`<br>153Default: `5000`154155Milliseconds to wait for the child process to terminate before sending `SIGKILL`.156157#### cancel()158159Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.160
317 unmodified lines
modified:test.js+61 added
114 unmodified lines
115 const {exitCode} = execa.sync('fail', {reject: false});116 t.is(exitCode, 2);117});118119test('execa() with .kill() after it with SIGKILL should kill cleanly', async t => {120 const subprocess = execa('node', ['fixtures/no-killable'], {121 stdio: ['ipc']122 });123124 await pEvent(subprocess, 'message');125126 subprocess.kill('SIGKILL');127128 const {signal} = await t.throwsAsync(subprocess);129 t.is(signal, 'SIGKILL');130});131132// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).133// Therefore, this feature and those tests do not make sense on Windows.134if (process.platform !== 'win32') {135 test('execa() with .kill() after it with SIGTERM should not kill (no retry)', async t => {136 const subprocess = execa('node', ['fixtures/no-killable'], {137 stdio: ['ipc']138 });139140 await pEvent(subprocess, 'message');141142 subprocess.kill('SIGTERM', {143 forceKill: false,144 forceKillAfter: 50145 });146147 t.true(isRunning(subprocess.pid));148 subprocess.kill('SIGKILL');149 });150151 test('execa() with .kill() after it with SIGTERM should kill after 50 ms with SIGKILL', async t => {152 const subprocess = execa('node', ['fixtures/no-killable'], {153 stdio: ['ipc']154 });155156 await pEvent(subprocess, 'message');157158 subprocess.kill('SIGTERM', {159 forceKillAfter: 50160 });161162 const {signal} = await t.throwsAsync(subprocess);163 t.is(signal, 'SIGKILL');164 });165166 test('execa() with .kill() after it with nothing (undefined) should kill after 50 ms with SIGKILL', async t => {167 const subprocess = execa('node', ['fixtures/no-killable'], {168 stdio: ['ipc']169 });170171 await pEvent(subprocess, 'message');172173 subprocess.kill();174175 const {signal} = await t.throwsAsync(subprocess);176 t.is(signal, 'SIGKILL');177 });178}179180test('stripFinalNewline: true', async t => {181 const {stdout} = await execa('noop', ['foo']);182 t.is(stdout, 'foo');183});
617 unmodified lines