Improve graceful exit (#714)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 8ef8e90 · Browse files · 8 files·+168 added−122 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+168 added−122 removed
- tests:+79 added−25 removed
- other:+89 added−97 removed
Provenance
- Commit
5eeaab5- Tree
417bba1- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
8ef8e90
8 files changed+168 added−122 removed
modified:lib/kill.js+18 added-19 removed
1223456788910111011121315161415161718192021202122232425262627282930293031313233343536376 unmodified lines4445464746484950515253545355565758595859606162632 unmodified lines66676869707071727374757576777878import os from 'node:os';import {setTimeout as pSetTimeout} from 'node:timers/promises';import {setTimeout} from 'node:timers/promises';import {onExit} from 'signal-exit';
const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behaviorexport const spawnedKill = (kill, signal = 'SIGTERM', {forceKillAfterTimeout = true} = {}) => {export const spawnedKill = (kill, {forceKillAfterTimeout}, controller, signal) => { const killResult = kill(signal); const timeout = getForceKillAfterTimeout(signal, forceKillAfterTimeout, killResult); setKillTimeout(kill, timeout); setKillTimeout({kill, signal, forceKillAfterTimeout, killResult, controller}); return killResult;};
const setKillTimeout = async (kill, timeout) => { if (timeout === undefined) {const setKillTimeout = async ({kill, signal, forceKillAfterTimeout, killResult, controller}) => { if (!shouldForceKill(signal, forceKillAfterTimeout, killResult)) { return; }
try { await pSetTimeout(timeout, undefined, {ref: false}); kill('SIGKILL'); await setTimeout(forceKillAfterTimeout, undefined, {signal: controller.signal}); kill('SIGKILL'); } catch {}};
const shouldForceKill = (signal, forceKillAfterTimeout, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
const isSigterm = signal => signal === os.constants.signals.SIGTERMconst isSigterm = signal => signal === undefined || signal === os.constants.signals.SIGTERM || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
const getForceKillAfterTimeout = (signal, forceKillAfterTimeout, killResult) => { if (!shouldForceKill(signal, forceKillAfterTimeout, killResult)) { return;export const normalizeForceKillAfterTimeout = forceKillAfterTimeout => { if (forceKillAfterTimeout === false) { return forceKillAfterTimeout; }
if (forceKillAfterTimeout === true) { return DEFAULT_FORCE_KILL_TIMEOUT;6 unmodified lines return forceKillAfterTimeout;};
const killAfterTimeout = async ({spawned, timeout, killSignal, context, controller}) => { await pSetTimeout(timeout, undefined, {ref: false, signal: controller.signal}); await setTimeout(timeout, undefined, {signal: controller.signal}); spawned.kill(killSignal); Object.assign(context, {timedOut: true, signal: killSignal}); throw new Error('Timed out');};
// `timeout` option handlingexport const throwOnTimeout = ({spawned, timeout, killSignal, context, finalizers}) => {export const throwOnTimeout = ({spawned, timeout, killSignal, context, controller}) => { if (timeout === 0 || timeout === undefined) { return []; }
const controller = new AbortController(); finalizers.push(controller.abort.bind(controller)); return [killAfterTimeout({spawned, timeout, killSignal, context, controller})];};
export const validateTimeout = ({timeout}) => {2 unmodified lines }};
// `cleanup` option handlingexport const cleanupOnExit = (spawned, cleanup, detached, finalizers) => {export const cleanupOnExit = (spawned, cleanup, detached) => { if (!cleanup || detached) { return; }
const removeExitHandler = onExit(() => { return onExit(() => { spawned.kill(); }); finalizers.push(removeExitHandler);};modified:lib/stream.js+8 added-9 removed
104 unmodified lines105 }106 };107 108 // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)109-export const getSpawnedResult = async (109+export const getSpawnedResult = async ({110 spawned,111- {encoding, buffer, maxBuffer, timeout, killSignal, cleanup, detached},111+ options: {encoding, buffer, maxBuffer, timeout, killSignal, cleanup, detached},112 context,113 stdioStreamsGroups,114-) => {115- const finalizers = [];116- cleanupOnExit(spawned, cleanup, detached, finalizers);114+ controller,115+}) => {116+ const removeExitHandler = cleanupOnExit(spawned, cleanup, detached);117 const customStreams = getCustomStreams(stdioStreamsGroups);118 119 const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));120 const allPromise = getAllPromise({spawned, encoding, buffer, maxBuffer});7 unmodified lines128 ...waitForCustomStreamsEnd(customStreams),129 ]),130 ...throwOnCustomStreamsError(customStreams),131 ...throwIfStreamError(spawned.stdin),132- ...throwOnTimeout({spawned, timeout, killSignal, context, finalizers}),132+ ...throwOnTimeout({spawned, timeout, killSignal, context, controller}),133 ]);134 } catch (error) {135 spawned.kill();136 const results = await Promise.all([3 unmodified lines140 ]);141 cleanupStdioStreams(customStreams, error);142 return results;143 } finally {144- for (const finalizer of finalizers) {145- finalizer();146- }144+ controller.abort();145+ removeExitHandler?.();146 }147 };modified:test/fixtures/no-killable.js+5 added-3 removed
1234564567891011121314#!/usr/bin/env nodeimport process from 'node:process';
process.on('SIGTERM', () => { console.log('Received SIGTERM, but we ignore it');});const noop = () => {};
process.on('SIGTERM', noop);process.on('SIGINT', noop);
process.send('');console.log('.');
setInterval(() => { // Run forever}, 20_000);modified:test/kill.js+74 added-22 removed
8 unmodified lines9 setFixtureDir();10 11 const TIMEOUT_REGEXP = /timed out after/;12 13-test('kill("SIGKILL") should terminate cleanly', async t => {14- const subprocess = execa('no-killable.js', {stdio: ['ipc']});13+const spawnNoKillable = async (forceKillAfterTimeout, options) => {14+ const subprocess = execa('no-killable.js', {15+ stdio: ['pipe', 'pipe', 'pipe', 'ipc'],16+ forceKillAfterTimeout,17+ ...options,18+ });19 await pEvent(subprocess, 'message');20+ return {subprocess};21+};22 23+test('kill("SIGKILL") should terminate cleanly', async t => {24+ const {subprocess} = await spawnNoKillable();25+26 subprocess.kill('SIGKILL');27 19- const {signal} = await t.throwsAsync(subprocess);28+ const {isTerminated, signal} = await t.throwsAsync(subprocess);29+ t.true(isTerminated);30 t.is(signal, 'SIGKILL');31 });32 33 // `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).34 // Therefore, this feature and those tests do not make sense on Windows.35 if (process.platform !== 'win32') {26- test('`forceKillAfterTimeout: false` should not kill after a timeout', async t => {27- const subprocess = execa('no-killable.js', {stdio: ['ipc']});28- await pEvent(subprocess, 'message');36+ const testNoForceKill = async (t, forceKillAfterTimeout, killArgument) => {37+ const {subprocess} = await spawnNoKillable(forceKillAfterTimeout);38 30- subprocess.kill('SIGTERM', {forceKillAfterTimeout: false});39+ subprocess.kill(killArgument);40 41+ await setTimeout(6e3);42 t.true(isRunning(subprocess.pid));43 subprocess.kill('SIGKILL');44 35- const {signal} = await t.throwsAsync(subprocess);45+ const {isTerminated, signal} = await t.throwsAsync(subprocess);46+ t.true(isTerminated);47 t.is(signal, 'SIGKILL');37- });48+ };49 39- const testForceKill = async (t, killArguments) => {40- const subprocess = execa('no-killable.js', {stdio: ['ipc']});41- await pEvent(subprocess, 'message');50+ test('`forceKillAfterTimeout: false` should not kill after a timeout', testNoForceKill, false);51+ test('`forceKillAfterTimeout` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');52 43- subprocess.kill(...killArguments);53+ const testForceKill = async (t, forceKillAfterTimeout, killArgument) => {54+ const {subprocess} = await spawnNoKillable(forceKillAfterTimeout);55 56+ subprocess.kill(killArgument);57+45- const {signal} = await t.throwsAsync(subprocess);58+ const {isTerminated, signal} = await t.throwsAsync(subprocess);59+ t.true(isTerminated);60 t.is(signal, 'SIGKILL');61 };62 49- test('`forceKillAfterTimeout: number` should kill after a timeout', testForceKill, ['SIGTERM', {forceKillAfterTimeout: 50}]);50- test('`forceKillAfterTimeout: true` should kill after a timeout', testForceKill, ['SIGTERM', {forceKillAfterTimeout: true}]);51- test('kill("SIGTERM") should kill after a timeout', testForceKill, ['SIGTERM']);52- test('kill() with no arguments should kill after a timeout', testForceKill, []);63+ test('`forceKillAfterTimeout: number` should kill after a timeout', testForceKill, 50);64+ test('`forceKillAfterTimeout: true` should kill after a timeout', testForceKill, true);65+ test('`forceKillAfterTimeout: undefined` should kill after a timeout', testForceKill, undefined);66+ test('`forceKillAfterTimeout` should kill after a timeout with the killSignal', testForceKill, 50, 'SIGTERM');67 68 const testInvalidForceKill = async (t, forceKillAfterTimeout) => {55- const childProcess = execa('noop.js');69 t.throws(() => {57- childProcess.kill('SIGTERM', {forceKillAfterTimeout});70+ execa('empty.js', {forceKillAfterTimeout});71 }, {instanceOf: TypeError, message: /non-negative integer/});59- const {signal} = await t.throwsAsync(childProcess);60- t.is(signal, 'SIGTERM');72 };73 74 test('`forceKillAfterTimeout` should not be NaN', testInvalidForceKill, Number.NaN);75 test('`forceKillAfterTimeout` should not be negative', testInvalidForceKill, -1);76+77+ test('`forceKillAfterTimeout` works with the "signal" option', async t => {78+ const abortController = new AbortController();79+ const {subprocess} = await spawnNoKillable(1, {signal: abortController.signal});80+ abortController.abort();81+ const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);82+ t.false(isTerminated);83+ t.is(signal, undefined);84+ t.true(isCanceled);85+ });86+87+ test.serial('`forceKillAfterTimeout` works with the "timeout" option', async t => {88+ const {subprocess} = await spawnNoKillable(1, {timeout: 2e3});89+ const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);90+ t.true(isTerminated);91+ t.is(signal, 'SIGTERM');92+ t.true(timedOut);93+ });94+95+ test('`forceKillAfterTimeout` works with the "maxBuffer" option', async t => {96+ const {subprocess} = await spawnNoKillable(1, {maxBuffer: 1});97+ const {isTerminated, signal} = await t.throwsAsync(subprocess);98+ t.false(isTerminated);99+ t.is(signal, undefined);100+ });101+102+ test('`forceKillAfterTimeout` works with "error" events on childProcess', async t => {103+ const {subprocess} = await spawnNoKillable(1);104+ subprocess.emit('error', new Error('test'));105+ const {isTerminated, signal} = await t.throwsAsync(subprocess);106+ t.false(isTerminated);107+ t.is(signal, undefined);108+ });109+110+ test('`forceKillAfterTimeout` works with "error" events on childProcess.stdout', async t => {111+ const {subprocess} = await spawnNoKillable(1);112+ subprocess.stdout.destroy(new Error('test'));113+ const {isTerminated, signal} = await t.throwsAsync(subprocess);114+ t.false(isTerminated);115+ t.is(signal, undefined);116+ });117 }118 119 test('execa() returns a promise with kill()', async t => {120 const subprocess = execa('noop.js', ['foo']);187 unmodified linesmodified:index.d.ts+20 added-27 removed
467 unmodified lines468 */469 readonly killSignal?: string | number;470 471 /**472+ If the child process is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).473+474+ The grace period is 5 seconds by default. This feature can be disabled with `false`.475+476+ This works when the child process is terminated by either:477+ - the `signal`, `timeout`, `maxBuffer` or `cleanup` option478+ - calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments479+480+ This does not work when the child process is terminated by either:481+ - calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with an argument482+ - calling [`process.kill(subprocess.pid)`](https://nodejs.org/api/process.html#processkillpid-signal)483+ - sending a termination signal from another process484+485+ Also, this does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events): `SIGKILL` and `SIGTERM` both terminate the process immediately. Other packages (such as [`taskkill`](https://github.com/sindresorhus/taskkill)) can be used to achieve fail-safe termination on Windows.486+487+ @default 5000488+ */489+ forceKillAfterTimeout?: number | false;490+491+ /**492 If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.493 494 @default false495 */244 unmodified lines740 741 export type ExecaError<OptionsType extends Options = Options> = ExecaCommonReturnValue<false, OptionsType> & ExecaCommonError;742 export type ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonReturnValue<true, OptionsType> & ExecaCommonError;743 724-export type KillOptions = {725- /**726- Milliseconds to wait for the child process to terminate before sending `SIGKILL`.727-728- Can be disabled with `false`.729-730- @default 5000731- */732- forceKillAfterTimeout?: number | false;733-};734-744 type StreamUnlessIgnored<745 StreamIndex extends string,746 OptionsType extends Options = Options,747 > = ChildProcessStream<IgnoresStreamResult<StreamIndex, OptionsType>>;40 unmodified lines788 onRejected?: (reason: ExecaError<OptionsType>) => ResultType | PromiseLike<ResultType>789 ): Promise<ExecaReturnValue<OptionsType> | ResultType>;790 791 /**783- 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`. Note that this graceful termination does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events) (`SIGKILL` and `SIGTERM` has the same effect of force-killing the process immediately.) If you want to achieve graceful termination on Windows, you have to use other means, such as [`taskkill`](https://github.com/sindresorhus/taskkill).784- */785- kill(signal?: string, options?: KillOptions): void;786-787- /**792 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process's `stdout` to `target`, which can be:793 - Another `execa()` return value794 - A writable stream795 - A file path string124 unmodified lines920 }921 \*\/922 }923 ```920-921-@example <caption>Graceful termination</caption>922-```923-const subprocess = execa('node');924-925-setTimeout(() => {926- subprocess.kill('SIGTERM', {927- forceKillAfterTimeout: 2000928- });929-}, 1000);930-```924 */925 export function execa<OptionsType extends Options = {}>(926 file: string | URL,927 arguments?: readonly string[],358 unmodified linesmodified:index.js+10 added-5 removed
8 unmodified lines9 import {makeError} from './lib/error.js';10 import {handleInputAsync, pipeOutputAsync} from './lib/stdio/async.js';11 import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';12 import {normalizeStdioNode} from './lib/stdio/normalize.js';13-import {spawnedKill, validateTimeout} from './lib/kill.js';13+import {spawnedKill, validateTimeout, normalizeForceKillAfterTimeout} from './lib/kill.js';14 import {addPipeMethods} from './lib/pipe.js';15 import {getSpawnedResult, makeAllStream} from './lib/stream.js';16 import {mergePromise} from './lib/promise.js';17 import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';34 unmodified lines52 const options = addDefaultOptions(initialOptions);53 validateTimeout(options);54 options.shell = normalizeFileUrl(options.shell);55 options.env = getEnv(options);56+ options.forceKillAfterTimeout = normalizeForceKillAfterTimeout(options.forceKillAfterTimeout);57 58 if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {59 // #11660 args.unshift('/q');19 unmodified lines80 all = false,81 windowsHide = true,82 verbose = verboseDefault,83 killSignal = 'SIGTERM',84+ forceKillAfterTimeout = true,85 ...options86 }) => ({87 ...options,88 maxBuffer,10 unmodified lines99 all,100 windowsHide,101 verbose,102 killSignal,103+ forceKillAfterTimeout,104 });105 106 const handleOutput = (options, value) => {107 if (value === undefined || value === null) {34 unmodified lines142 mergePromise(dummySpawned, errorPromise);143 return dummySpawned;144 }145 146+ const controller = new AbortController();147+148 pipeOutputAsync(spawned, stdioStreamsGroups);149 145- spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));150+ spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned), options, controller);151 spawned.all = makeAllStream(spawned, options);152 153 addPipeMethods(spawned);154 150- const promise = handlePromise({spawned, options, stdioStreamsGroups, command, escapedCommand});155+ const promise = handlePromise({spawned, options, stdioStreamsGroups, command, escapedCommand, controller});156 mergePromise(spawned, promise);157 return spawned;158 }159 155-const handlePromise = async ({spawned, options, stdioStreamsGroups, command, escapedCommand}) => {160+const handlePromise = async ({spawned, options, stdioStreamsGroups, command, escapedCommand, controller}) => {161 const context = {timedOut: false};162 163 const [164 [exitCode, signal, error],165 stdioResults,166 allResult,162- ] = await getSpawnedResult(spawned, options, context, stdioStreamsGroups);167+ ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, controller});168 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));169 const all = handleOutput(options, allResult);170 171 if (error || exitCode !== 0 || signal !== null) {172 unmodified linesmodified:index.test-d.ts+9 added-4 removed
1185 unmodified lines1186 execa('unicorns', {killSignal: 'SIGTERM'});1187 execaSync('unicorns', {killSignal: 'SIGTERM'});1188 execa('unicorns', {killSignal: 9});1189 execaSync('unicorns', {killSignal: 9});1190+execa('unicorns', {forceKillAfterTimeout: false});1191+execaSync('unicorns', {forceKillAfterTimeout: false});1192+execa('unicorns', {forceKillAfterTimeout: 42});1193+execaSync('unicorns', {forceKillAfterTimeout: 42});1194+execa('unicorns', {forceKillAfterTimeout: undefined});1195+execaSync('unicorns', {forceKillAfterTimeout: undefined});1196+expectError(execa('unicorns', {forceKillAfterTimeout: 'true'}));1197+expectError(execaSync('unicorns', {forceKillAfterTimeout: 'true'}));1198 execa('unicorns', {signal: new AbortController().signal});1199 expectError(execaSync('unicorns', {signal: new AbortController().signal}));1200 execa('unicorns', {windowsVerbatimArguments: true});1201 execaSync('unicorns', {windowsVerbatimArguments: true});4 unmodified lines1206 /* eslint-enable @typescript-eslint/no-floating-promises */1207 execa('unicorns').kill();1208 execa('unicorns').kill('SIGKILL');1209 execa('unicorns').kill(undefined);1202-execa('unicorns').kill('SIGKILL', {});1203-execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: false});1204-execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: 42});1205-execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: undefined});1210+expectError(execa('unicorns').kill('SIGKILL', {}));1211 1212 expectError(execa(['unicorns', 'arg']));1213 expectType<ExecaChildProcess>(execa('unicorns'));1214 expectType<ExecaChildProcess>(execa(fileUrl));99 unmodified linesmodified:readme.md+24 added-33 removed
48 unmodified lines49 - [Cleans up](#cleanup) child processes when the parent process ends.50 - Redirect [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1) from/to files, streams, iterables, strings, `Uint8Array` or [objects](docs/transform.md#object-mode).51 - [Transform](docs/transform.md) `stdin`/`stdout`/`stderr` with simple functions.52 - Iterate over [each text line](docs/transform.md#binary-data) output by the process.53-- [Graceful termination](#optionsforcekillaftertimeout).53+- [Fail-safe process termination](#forcekillaftertimeout).54 - Get [interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal.55 - [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.56 - Convenience methods to pipe processes' [input](#input) and [output](#redirect-output-to-a-file).57 - Can specify file and arguments [as a single string](#execacommandcommand-options) without a shell.162 unmodified lines220 */221 }222 ```223 224-### Graceful termination225-226-Using SIGTERM, and after 2 seconds, kill it with SIGKILL.227-228-```js229-const subprocess = execa('node');230-231-setTimeout(() => {232- subprocess.kill('SIGTERM', {233- forceKillAfterTimeout: 2000234- });235-}, 1000);236-```237-224 ## API225 226 ### Methods227 80 unmodified lines308 The return value of all [asynchronous methods](#methods) is both:309 - a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).310 - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with the following additional methods and properties.311 326-#### kill(signal?, options?)327-328-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`.329-330-Note that this graceful termination does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events) (`SIGKILL` and `SIGTERM` has the same effect of force-killing the process immediately.) If you want to achieve graceful termination on Windows, you have to use other means, such as [`taskkill`](https://github.com/sindresorhus/taskkill).331-332-##### options.forceKillAfterTimeout333-334-Type: `number | false`\335-Default: `5000`336-337-Milliseconds to wait for the child process to terminate before sending `SIGKILL`.338-339-Can be disabled with `false`.340-312 #### all313 314 Type: `ReadableStream | undefined`315 122 unmodified lines438 439 Type: `boolean`440 441 Whether the process was terminated using either:471-- [`childProcess.kill()`](#killsignal-options).442+- `childProcess.kill()`.443 - A signal sent by another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).444 445 #### signal446 447 Type: `string | undefined`448 449 The name of the signal (like `SIGFPE`) that terminated the process using either:479-- [`childProcess.kill()`](#killsignal-options).450+- `childProcess.kill()`.451 - A signal sent by another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).452 453 If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.454 298 unmodified lines753 Default: `SIGTERM`754 755 Signal value to be used when the spawned process will be killed.756 757+#### forceKillAfterTimeout758+759+Type: `number | false`\760+Default: `5000`761+762+If the child process is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).763+764+The grace period is 5 seconds by default. This feature can be disabled with `false`.765+766+This works when the child process is terminated by either:767+- the [`signal`](#signal-1), [`timeout`](#timeout), [`maxBuffer`](#maxbuffer) or [`cleanup`](#cleanup) option768+- calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments769+770+This does not work when the child process is terminated by either:771+- calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with an argument772+- calling [`process.kill(subprocess.pid)`](https://nodejs.org/api/process.html#processkillpid-signal)773+- sending a termination signal from another process774+775+Also, this does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events): `SIGKILL` and `SIGTERM` both terminate the process immediately. Other packages (such as [`taskkill`](https://github.com/sindresorhus/taskkill)) can be used to achieve fail-safe termination on Windows.776+777 #### signal778 779 Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)780 70 unmodified lines851 ```852 853 ### Retry on error854 864-Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:855+Safely handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:856 857 ```js858 import pRetry from 'p-retry';859 81 unmodified lines