termination.md
This file
Path
docs/termination.md
311 lines · 12.2 KiB · Markdown
Last changed by
Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
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## Timeout126Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 127why, one step back127If 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 128–143why, one step back128129```js130try {131 await execa({timeout: 5000})`npm run build`;132} catch (error) {133 if (error.timedOut) {134 console.error('Timed out.');135 }136137 throw error;138}139```140141## Current process exit142143If the current process exits, the subprocess is automatically [terminated](#default-signal) unless either:Move API reference to its own page (#996)ehmickybefore adoption7cde496
lines 144–145why, one step back144- The [`cleanup`](api.md#optionscleanup) option is `false`.145- The subprocess is run in the background using the [`detached`](api.md#optionsdetached) option.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 146–149why, one step back146- The current process was terminated abruptly, for example, with [`SIGKILL`](#sigkill) as opposed to [`SIGTERM`](#sigterm) or a successful exit.147148## Signal termination149Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 150why, one step back150[`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 151–155why, one step back151152[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)153154### SIGTERM155Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 156why, one step back156[`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 157–164why, one step back157158```js159const subprocess = execa`npm run build`;160subprocess.kill();161// Is the same as:162subprocess.kill('SIGTERM');163```164Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 165why, one step back165### SIGINTAdd user guides (#989)ehmickybefore adoptionbe91ecf
line 166why, one step back166Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
lines 167–168why, one step back167[`SIGINT`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGINT) terminates the process. Its [handler](#handling-signals) is triggered on `CTRL-C`.168Add user guides (#989)ehmickybefore adoptionbe91ecf
line 169why, one step back169```jsImprove documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 170why, one step back170subprocess.kill('SIGINT');Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 171–174why, one step back171```172173### SIGKILL174Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 175why, one step back175[`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 176–180why, one step back176177```js178subprocess.kill('SIGKILL');179```180Document `SIGQUIT` (#1022)ehmickybefore adoptionc5bd9d8
lines 181–182why, one step back181### SIGQUIT182Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 183why, one step back183[`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 184–188why, one step back184185```js186subprocess.kill('SIGQUIT');187```188Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 189–194why, one step back189### Other signals190191Other 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).192193### Default signal194Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 195why, one step back195The [`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 196–200why, one step back196197```js198const subprocess = execa({killSignal: 'SIGKILL'})`npm run build`;199subprocess.kill(); // Forceful termination200```Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
lines 201–213why, one step back201202### Handling signals203204On Unix, most signals (not [`SIGKILL`](#sigkill)) can be intercepted to perform a graceful exit.205206```js207process.on('SIGTERM', () => {208 cleanup();209 process.exit(1);210})211```212213Unfortunately 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 214–215why, one step back214215Execa provides the [`gracefulCancel`](#graceful-termination) option as a cross-platform alternative to signal handlers.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 216–218why, one step back216217### Signal name and description218Improve documentation of `error.*` fields (#1006)ehmickybefore adoption4ee0dec
line 219why, one step back219When a subprocess was terminated by a signal, [`error.isTerminated`](api.md#erroristerminated) is `true`.Add user guides (#989)ehmickybefore adoptionbe91ecf
line 220why, one step back220Improve documentation of `error.*` fields (#1006)ehmickybefore adoption4ee0dec
line 221why, one step back221Also, [`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 222–239why, one step back222223```js224try {225 await execa`npm run build`;226} catch (error) {227 if (error.isTerminated) {228 console.error(error.signal); // SIGFPE229 console.error(error.signalDescription); // 'Floating point arithmetic error'230 }231232 throw error;233}234```235236## Forceful termination237238If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.239Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 240why, one step back240The 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 241why, one step back241Add `error.isForcefullyTerminated` (#1111)ehmickybefore adoptione69985d
lines 242–243why, one step back242The [`error.isForcefullyTerminated`](api.md#errorisforcefullyterminated) boolean property can be used to check whether a subprocess was forcefully terminated by the `forceKillAfterDelay` option.243Add user guides (#989)ehmickybefore adoptionbe91ecf
line 244why, one step back244This works when the subprocess is terminated by either:Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 245why, one step back245- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with no arguments.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 246–248why, one step back246- The [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) or [`cleanup`](#current-process-exit) option.247248This does not work when the subprocess is terminated by either:Move API reference to its own page (#996)ehmickybefore adoption7cde496
lines 249–250why, one step back249- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with a specific signal.250- Calling [`process.kill(subprocess.pid)`](api.md#subprocesspid).Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 251–262why, one step back251- Sending a termination signal [from another process](#inter-process-termination).252253Also, 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.254255```js256// No forceful termination257const subprocess = execa({forceKillAfterDelay: false})`npm run build`;258subprocess.kill();259```260261## Inter-process termination262Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08
line 263why, one step back263[`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 264–270why, one step back264265```js266const subprocess = execa`npm run build`;267console.log('PID:', subprocess.pid); // PID: 6513268await subprocess;269```270Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08
lines 271–272why, one step back271For example, from a terminal:272Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 273–274why, one step back273```sh274$ kill -SIGTERM 6513Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08
lines 275–282why, one step back275```276277Or from a different Node.js process:278279```js280import process from 'node:process';281282process.kill(subprocessPid);Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 283–286why, one step back283```284285## Error message and stack trace286Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 287why, one step back287When 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 288–311why, one step back288289```js290try {291 const subprocess = execa`npm run build`;292 setTimeout(() => {293 subprocess.kill(new Error('Timed out after 5 seconds.'));294 }, 5000);295 await subprocess;296} catch (error) {297 if (error.isTerminated) {298 console.error(error.cause); // new Error('Timed out after 5 seconds.')299 console.error(error.cause.stack); // Stack trace from `error.cause`300 console.error(error.originalMessage); // 'Timed out after 5 seconds.'301 }302303 throw error;304}305```306307<hr>308309[**Next**: 🎹 Input](input.md)\310[**Previous**: ❌ Errors](errors.md)\311[**Top**: Table of contents](../readme.md#documentation)