termination.md
This file
Path
docs/termination.md
358 lines · 13.5 KiB · Markdown
Last changed by
Document how to terminate hanging subprocesses (#1140)ehmickybefore adoptionc0b6efc
History of this fileTake it
Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 1–8why, one step back1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 🏁 Termination8Document alternatives to process termination (#1026)ehmickybefore adoption9d7eed8
lines 9–10why, one step back9## Alternatives10Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
line 11why, one step back11Terminating a subprocess ends it abruptly. This prevents rolling back the subprocess' operations and leaves them incomplete.Document alternatives to process termination (#1026)ehmickybefore adoption9d7eed8
line 12why, one step back12Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
lines 13–14why, one step back13Ideally subprocesses should end on their own. If that's not possible, [graceful termination](#graceful-termination) should be preferred.14Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 15–16why, one step back15## Canceling16Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
line 17why, one step back17The [`cancelSignal`](api.md#optionscancelsignal) option can be used to cancel a subprocess. When it is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), a [`SIGTERM` signal](#default-signal) is sent to the subprocess.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 18–19why, one step back1819```jsAdd `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
line 20why, one step back20import {execaNode} from 'execa';Add user guides (#989)ehmickybefore adoptionbe91ecf
line 21why, one step back21Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
lines 22–23why, one step back22const controller = new AbortController();23const cancelSignal = controller.signal;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 24–25why, one step back2425setTimeout(() => {Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
line 26why, one step back26 controller.abort();Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 27–29why, one step back27}, 5000);2829try {Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
line 30why, one step back30 await execaNode({cancelSignal})`build.js`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 31–32why, one step back31} catch (error) {32 if (error.isCanceled) {Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
line 33why, one step back33 console.error('Canceled by cancelSignal.');Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 34–39why, one step back34 }3536 throw error;37}38```39Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
lines 40–124why, one step back40## Graceful termination4142### Share a `cancelSignal`4344When the [`gracefulCancel`](api.md#optionsgracefulcancel) option is `true`, the [`cancelSignal`](api.md#optionscancelsignal) option does not send any [`SIGTERM`](#sigterm). Instead, the subprocess calls [`getCancelSignal()`](api.md#getcancelsignal) to retrieve and handle the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). This allows the subprocess to properly clean up and abort operations.4546This option only works with Node.js files.4748This is cross-platform. If you do not need to support Windows, [signal handlers](#handling-signals) can also be used.4950```js51// main.js52import {execaNode} from 'execa';5354const controller = new AbortController();55const cancelSignal = controller.signal;5657setTimeout(() => {58 controller.abort();59}, 5000);6061try {62 await execaNode({cancelSignal, gracefulCancel: true})`build.js`;63} catch (error) {64 if (error.isGracefullyCanceled) {65 console.error('Cancelled gracefully.');66 }6768 throw error;69}70```7172```js73// build.js74import {getCancelSignal} from 'execa';7576const cancelSignal = await getCancelSignal();77```7879### Abort operations8081The [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) returned by [`getCancelSignal()`](api.md#getcancelsignal) can be passed to most long-running Node.js methods: [`setTimeout()`](https://nodejs.org/api/timers.html#timerspromisessettimeoutdelay-value-options), [`setInterval()`](https://nodejs.org/api/timers.html#timerspromisessetintervaldelay-value-options), [events](https://nodejs.org/api/events.html#eventsonemitter-eventname-options), [streams](https://nodejs.org/api/stream.html#new-streamreadableoptions), [REPL](https://nodejs.org/api/readline.html#rlquestionquery-options), HTTP/TCP [requests](https://nodejs.org/api/http.html#httprequesturl-options-callback) or [servers](https://nodejs.org/api/net.html#serverlistenoptions-callback), [reading](https://nodejs.org/api/fs.html#fspromisesreadfilepath-options) / [writing](https://nodejs.org/api/fs.html#fspromiseswritefilefile-data-options) / [watching](https://nodejs.org/api/fs.html#fspromiseswatchfilename-options) files, or spawning another subprocess.8283When aborted, those methods throw the `Error` instance which was passed to [`abortController.abort(error)`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort). Since those methods keep the subprocess alive, aborting them makes the subprocess end on its own.8485```js86import {getCancelSignal} from 'execa';87import {watch} from 'node:fs/promises';8889const cancelSignal = await getCancelSignal();9091try {92 for await (const fileChange of watch('./src', {signal: cancelSignal})) {93 onFileChange(fileChange);94 }95} catch (error) {96 if (error.isGracefullyCanceled) {97 console.log(error.cause === cancelSignal.reason); // true98 }99}100```101102### Cleanup logic103104For other kinds of operations, the [`abort`](https://nodejs.org/api/globals.html#event-abort) event should be listened to. Although [`cancelSignal.addEventListener('abort')`](https://nodejs.org/api/events.html#eventtargetaddeventlistenertype-listener-options) can be used, [`events.addAbortListener(cancelSignal)`](https://nodejs.org/api/events.html#eventsaddabortlistenersignal-listener) is preferred since it works even if the `cancelSignal` is already aborted.105106### Graceful exit107108We recommend explicitly [stopping](#abort-operations) each pending operation when the subprocess is aborted. This allows it to end on its own.109110```js111import {getCancelSignal} from 'execa';112import {addAbortListener} from 'node:events';113114const cancelSignal = await getCancelSignal();115addAbortListener(cancelSignal, async () => {116 await cleanup();117 process.exitCode = 1;118});119```120121However, if any operation is still ongoing, the subprocess will keep running. It can be forcefully ended using [`process.exit(exitCode)`](https://nodejs.org/api/process.html#processexitcode) instead of [`process.exitCode`](https://nodejs.org/api/process.html#processexitcode_1).122123If the subprocess is still alive after 5 seconds, it is forcefully terminated with [`SIGKILL`](#sigkill). This can be [configured or disabled](#forceful-termination) using the [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option.124Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 125–126why, one step back125## Timeout126Document how to terminate hanging subprocesses (#1140)ehmickybefore adoptionc0b6efc
lines 127–128why, one step back127### Execution timeout128Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 129why, one step back129If the subprocess lasts longer than the [`timeout`](api.md#optionstimeout) option, a [`SIGTERM` signal](#default-signal) is sent to it.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 130–140why, one step back130131```js132try {133 await execa({timeout: 5000})`npm run build`;134} catch (error) {135 if (error.timedOut) {136 console.error('Timed out.');137 }138139 throw error;140}Document how to terminate hanging subprocesses (#1140)ehmickybefore adoptionc0b6efc
lines 141–185why, one step back141```142143### Inactivity timeout144145To terminate a subprocess when it becomes inactive, the [`cancelSignal`](#canceling) option can be combined with [transforms](transform.md) and some [debouncing logic](https://github.com/sindresorhus/debounce-fn). The following example terminates the subprocess if it has not printed to [`stdout`](api.md#resultstdout)/[`stderr`](api.md#resultstderr) in the last minute.146147```js148import {execa} from 'execa';149import debounceFn from 'debounce-fn';150151// 1 minute152const wait = 60_000;153154const getInactivityOptions = () => {155 const controller = new AbortController();156 const cancelSignal = controller.signal;157158 // Delay and debounce `cancelSignal` each time `controller.abort()` is called159 const scheduleAbort = debounceFn(controller.abort.bind(controller), {wait});160161 const onOutput = {162 * transform(data) {163 // When anything is printed, debounce `controller.abort()`164 scheduleAbort();165166 // Keep the output as is167 yield data;168 },169 // Debounce even if the output does not include any newline170 binary: true,171 };172173 // Start debouncing174 scheduleAbort();175176 return {177 cancelSignal,178 stdout: onOutput,179 stderr: onOutput,180 };181};182183const options = getInactivityOptions();184185await execa(options)`npm run build`;Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 186–190why, one step back186```187188## Current process exit189190If the current process exits, the subprocess is automatically [terminated](#default-signal) unless either:Move API reference to its own page (#996)ehmickybefore adoption7cde496
lines 191–192why, one step back191- The [`cleanup`](api.md#optionscleanup) option is `false`.192- The subprocess is run in the background using the [`detached`](api.md#optionsdetached) option.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 193–196why, one step back193- The current process was terminated abruptly, for example, with [`SIGKILL`](#sigkill) as opposed to [`SIGTERM`](#sigterm) or a successful exit.194195## Signal termination196Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 197why, one step back197[`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.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 198–202why, one step back198199[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)200201### SIGTERM202Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 203why, one step back203[`SIGTERM`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGTERM) is the default signal. It terminates the subprocess. On Unix, it can [be handled](#handling-signals) to run some cleanup logic.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 204–211why, one step back204205```js206const subprocess = execa`npm run build`;207subprocess.kill();208// Is the same as:209subprocess.kill('SIGTERM');210```211Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 212why, one step back212### SIGINTAdd user guides (#989)ehmickybefore adoptionbe91ecf
line 213why, one step back213Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
lines 214–215why, one step back214[`SIGINT`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGINT) terminates the process. Its [handler](#handling-signals) is triggered on `CTRL-C`.215Add user guides (#989)ehmickybefore adoptionbe91ecf
line 216why, one step back216```jsImprove documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 217why, one step back217subprocess.kill('SIGINT');Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 218–221why, one step back218```219220### SIGKILL221Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 222why, one step back222[`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL) forcefully terminates the subprocess. It [cannot be handled](#handling-signals).Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 223–227why, one step back223224```js225subprocess.kill('SIGKILL');226```227Document `SIGQUIT` (#1022)ehmickybefore adoptionc5bd9d8
lines 228–229why, one step back228### SIGQUIT229Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 230why, one step back230[`SIGQUIT`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGQUIT) terminates the process. On Unix, it creates a [core dump](https://en.wikipedia.org/wiki/Core_dump).Document `SIGQUIT` (#1022)ehmickybefore adoptionc5bd9d8
lines 231–235why, one step back231232```js233subprocess.kill('SIGQUIT');234```235Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 236–241why, one step back236### Other signals237238Other signals can be passed as argument. However, most other signals do not fully [work on Windows](https://github.com/ehmicky/cross-platform-node-guide/blob/main/docs/6_networking_ipc/signals.md#cross-platform-signals).239240### Default signal241Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 242why, one step back242The [`killSignal`](api.md#optionskillsignal) option sets the default signal used by [`subprocess.kill()`](api.md#subprocesskillsignal-error) and the following options: [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) and [`cleanup`](#current-process-exit). It is [`SIGTERM`](#sigterm) by default.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 243–247why, one step back243244```js245const subprocess = execa({killSignal: 'SIGKILL'})`npm run build`;246subprocess.kill(); // Forceful termination247```Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
lines 248–260why, one step back248249### Handling signals250251On Unix, most signals (not [`SIGKILL`](#sigkill)) can be intercepted to perform a graceful exit.252253```js254process.on('SIGTERM', () => {255 cleanup();256 process.exit(1);257})258```259260Unfortunately this [usually does not work](https://github.com/ehmicky/cross-platform-node-guide/blob/main/docs/6_networking_ipc/signals.md#cross-platform-signals) on Windows. The only signal that is somewhat cross-platform is [`SIGINT`](#sigint): on Windows, its handler is triggered when the user types `CTRL-C` in the terminal. However `subprocess.kill('SIGINT')` is only handled on Unix.Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
lines 261–262why, one step back261262Execa provides the [`gracefulCancel`](#graceful-termination) option as a cross-platform alternative to signal handlers.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 263–265why, one step back263264### Signal name and description265Improve documentation of `error.*` fields (#1006)ehmickybefore adoption4ee0dec
line 266why, one step back266When a subprocess was terminated by a signal, [`error.isTerminated`](api.md#erroristerminated) is `true`.Add user guides (#989)ehmickybefore adoptionbe91ecf
line 267why, one step back267Improve documentation of `error.*` fields (#1006)ehmickybefore adoption4ee0dec
line 268why, one step back268Also, [`error.signal`](api.md#errorsignal) and [`error.signalDescription`](api.md#errorsignaldescription) indicate the signal's name and [human-friendly description](https://github.com/ehmicky/human-signals). On Windows, those are only set if the current process terminated the subprocess, as opposed to [another process](#inter-process-termination).Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 269–286why, one step back269270```js271try {272 await execa`npm run build`;273} catch (error) {274 if (error.isTerminated) {275 console.error(error.signal); // SIGFPE276 console.error(error.signalDescription); // 'Floating point arithmetic error'277 }278279 throw error;280}281```282283## Forceful termination284285If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.286Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 287why, one step back287The grace period is set by the [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option, which is 5 seconds by default. This feature can be disabled with `false`.Add user guides (#989)ehmickybefore adoptionbe91ecf
line 288why, one step back288Add `error.isForcefullyTerminated` (#1111)ehmickybefore adoptione69985d
lines 289–290why, one step back289The [`error.isForcefullyTerminated`](api.md#errorisforcefullyterminated) boolean property can be used to check whether a subprocess was forcefully terminated by the `forceKillAfterDelay` option.290Add user guides (#989)ehmickybefore adoptionbe91ecf
line 291why, one step back291This works when the subprocess is terminated by either:Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 292why, one step back292- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with no arguments.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 293–295why, one step back293- The [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) or [`cleanup`](#current-process-exit) option.294295This does not work when the subprocess is terminated by either:Move API reference to its own page (#996)ehmickybefore adoption7cde496
lines 296–297why, one step back296- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with a specific signal.297- Calling [`process.kill(subprocess.pid)`](api.md#subprocesspid).Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 298–309why, one step back298- Sending a termination signal [from another process](#inter-process-termination).299300Also, 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 subprocess immediately. Other packages (such as [`taskkill`](https://github.com/sindresorhus/taskkill)) can be used to achieve fail-safe termination on Windows.301302```js303// No forceful termination304const subprocess = execa({forceKillAfterDelay: false})`npm run build`;305subprocess.kill();306```307308## Inter-process termination309Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08
line 310why, one step back310[`subprocess.kill()`](api.md#subprocesskillsignal-error) only works when the current process terminates the subprocess. To terminate the subprocess from a different process, its [`subprocess.pid`](api.md#subprocesspid) can be used instead.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 311–317why, one step back311312```js313const subprocess = execa`npm run build`;314console.log('PID:', subprocess.pid); // PID: 6513315await subprocess;316```317Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08
lines 318–319why, one step back318For example, from a terminal:319Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 320–321why, one step back320```sh321$ kill -SIGTERM 6513Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08
lines 322–329why, one step back322```323324Or from a different Node.js process:325326```js327import process from 'node:process';328329process.kill(subprocessPid);Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 330–333why, one step back330```331332## Error message and stack trace333Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 334why, one step back334When terminating a subprocess, it is possible to include an error message and stack trace by using [`subprocess.kill(error)`](api.md#subprocesskillerror). The `error` argument will be available at [`error.cause`](api.md#errorcause).Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 335–358why, one step back335336```js337try {338 const subprocess = execa`npm run build`;339 setTimeout(() => {340 subprocess.kill(new Error('Timed out after 5 seconds.'));341 }, 5000);342 await subprocess;343} catch (error) {344 if (error.isTerminated) {345 console.error(error.cause); // new Error('Timed out after 5 seconds.')346 console.error(error.cause.stack); // Stack trace from `error.cause`347 console.error(error.originalMessage); // 'Timed out after 5 seconds.'348 }349350 throw error;351}352```353354<hr>355356[**Next**: 🎹 Input](input.md)\357[**Previous**: ❌ Errors](errors.md)\358[**Top**: Table of contents](../readme.md#documentation)