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
Provenance
- Commit
0bd5596- Tree
0c5d3a7- Author
zokker13 <zokker13@users.noreply.github.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
fcd3d85
6 files changed+153 added−1 removed
added:fixtures/no-killable+12 added
1+#!/usr/bin/env node2+'use strict';3+4+process.on('SIGTERM', () => {5+ console.log('Received SIGTERM, but we ignore it');6+});7+8+process.send('');9+10+setInterval(() => {11+ // Run forever12+}, 20000);modified:index.d.ts+21 added
277 unmodified lines278 */279 isCanceled: boolean;280 }281 282+ 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.285+286+ @default true287+ */288+ forceKill?: boolean;289+290+ /**291+ Milliseconds to wait for the child process to terminate before sending a `SIGKILL` signal.292+293+ @default 5000294+ */295+ forceKillAfter?: number;296+ }297+298 interface ExecaChildPromise<StdoutErrorType> {299 catch<ResultType = never>(300 onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>301 ): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;302 303 /**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;307+308+ /**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 linesmodified:index.js+25 added
211 unmodified lines212 213 return [file, ...args].join(' ');214 }215 216+function 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+}223+224 const 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 lines238 killed: false239 }));240 }241 242+ 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+ }255+256+ return killResult;257+ };258+259 // #115260 let removeExitHandler;261 if (parsed.options.cleanup && !parsed.options.detached) {262 removeExitHandler = onExit(() => {217 unmodified linesmodified:index.test-d.ts+8 added
117 unmodified linesExpand all11811912012112212312412512612712812913013113213336 unmodified lines117 unmodified linesExpand allexeca('unicorns', {maxBuffer: 1000});execa('unicorns', {killSignal: 'SIGTERM'});execa('unicorns', {killSignal: 9});execa('unicorns', {windowsVerbatimArguments: true});execa('unicorns').kill();execa('unicorns').kill('SIGKILL');execa('unicorns').kill(undefined);execa('unicorns').kill('SIGKILL', {});execa('unicorns').kill('SIGKILL', {forceKill: true});execa('unicorns').kill('SIGKILL', {forceKill: false});execa('unicorns').kill('SIGKILL', {forceKillAfter: 42});execa('unicorns').kill('SIGKILL', {forceKillAfter: undefined});
expectType<ExecaChildProcess<string>>(execa('unicorns'));expectType<ExecaReturnValue<string>>(await execa('unicorns'));expectType<ExecaReturnValue<string>>(36 unmodified linesmodified:readme.md+26 added-1 removed
110 unmodified lines111 killed: false112 }113 */114 }115+116+// Kill a process with SIGTERM, and after 2 seconds, kill it with SIGKILL117+const subprocess = execa('node');118+setTimeout(() => {119+ subprocess.kill('SIGTERM', {120+ forceKillAfter: 2000121+ });122+}, 1000);123 ```124 117-125 ## API126 127 ### execa(file, arguments, [options])128 6 unmodified lines135 Returns 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.138 139+#### kill([signal], [options])140+141+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`.142+143+##### options.forceKill144+145+Type: `boolean`<br>146+Default: `true`147+148+If the first signal does not terminate the child process after a specified timeout, a `SIGKILL` signal will be sent to the process.149+150+##### options.forceKillAfter151+152+Type: `string`<br>153+Default: `5000`154+155+Milliseconds to wait for the child process to terminate before sending `SIGKILL`.156+157 #### cancel()158 159 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`.160 317 unmodified linesmodified:test.js+61 added
114 unmodified lines115 const {exitCode} = execa.sync('fail', {reject: false});116 t.is(exitCode, 2);117 });118 119+test('execa() with .kill() after it with SIGKILL should kill cleanly', async t => {120+ const subprocess = execa('node', ['fixtures/no-killable'], {121+ stdio: ['ipc']122+ });123+124+ await pEvent(subprocess, 'message');125+126+ subprocess.kill('SIGKILL');127+128+ const {signal} = await t.throwsAsync(subprocess);129+ t.is(signal, 'SIGKILL');130+});131+132+// `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.134+if (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+ });139+140+ await pEvent(subprocess, 'message');141+142+ subprocess.kill('SIGTERM', {143+ forceKill: false,144+ forceKillAfter: 50145+ });146+147+ t.true(isRunning(subprocess.pid));148+ subprocess.kill('SIGKILL');149+ });150+151+ 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+ });155+156+ await pEvent(subprocess, 'message');157+158+ subprocess.kill('SIGTERM', {159+ forceKillAfter: 50160+ });161+162+ const {signal} = await t.throwsAsync(subprocess);163+ t.is(signal, 'SIGKILL');164+ });165+166+ 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+ });170+171+ await pEvent(subprocess, 'message');172+173+ subprocess.kill();174+175+ const {signal} = await t.throwsAsync(subprocess);176+ t.is(signal, 'SIGKILL');177+ });178+}179+180 test('stripFinalNewline: true', async t => {181 const {stdout} = await execa('noop', ['foo']);182 t.is(stdout, 'foo');183 });617 unmodified lines