termination.md
This file
Path
docs/termination.md
379 lines · 16.0 KiB · Markdown
Last changed by
TweaksSindre Sorhusbefore adoption698a1b8
History of this fileTake it
The walk stopped after 200 commits: lines older than 9f65b86 point at it.
100% test coverage (#1018)ehmickybefore adoption9f65b86
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.14100% test coverage (#1018)ehmickybefore adoption9f65b86
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.100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 18–19why, one step back1819```jsAdd `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
line 20why, one step back20import {execaNode} from 'execa';100% test coverage (#1018)ehmickybefore adoption9f65b86
line 21why, one step back21Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
lines 22–23why, one step back22const controller = new AbortController();23const cancelSignal = controller.signal;100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 24–25why, one step back2425setTimeout(() => {Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
line 26why, one step back26 controller.abort();100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 27–29why, one step back27}, 5000);2829try {Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
line 30why, one step back30 await execaNode({cancelSignal})`build.js`;100% test coverage (#1018)ehmickybefore adoption9f65b86
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.');100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 34–39why, one step back34 }3536 throw error;37}38```39Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
lines 40–120why, 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```120Require Node.js 22 (#1243)Sindre Sorhusbefore adoption04b4454
line 121why, one step back121However, 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).Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5
lines 122–124why, one step back122123If 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.124100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 125–126why, one step back125## Timeout126Document how to terminate hanging subprocesses (#1140)ehmickybefore adoptionc0b6efc
lines 127–128why, one step back127### Execution timeout128100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 129–140why, one step back129If the subprocess lasts longer than the [`timeout`](api.md#optionstimeout) option, a [`SIGTERM` signal](#default-signal) is sent to it.130131```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`;100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 186–194why, one step back186```187188## Current process exit189190If the current process exits, the subprocess is automatically [terminated](#default-signal) unless either:191- The [`cleanup`](api.md#optionscleanup) option is `false`.192- The subprocess is run in the background using the [`detached`](api.md#optionsdetached) option.193- The current process was terminated abruptly, for example, with [`SIGKILL`](#sigkill) as opposed to [`SIGTERM`](#sigterm) or a successful exit.194Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec
lines 195–211why, one step back195By default, only the subprocess is terminated, not the other processes it might have spawned. The [`killDescendants`](#killing-descendant-processes) option can be used to also terminate those.196197## Killing descendant processes198199By default, [terminating](#signal-termination) a subprocess only sends a signal to that subprocess, not to any process it might have spawned itself. For example, terminating a subprocess started with the [`shell`](api.md#optionsshell) option only terminates the shell, not the command it is running.200201The [`killDescendants`](api.md#optionskilldescendants) option terminates the whole process tree instead: the subprocess and all of its descendants. This applies to every way Execa terminates a subprocess, including [`subprocess.kill()`](#signal-termination), the [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) and [`cleanup`](#current-process-exit) options, and the [`forceKillAfterDelay`](#forceful-termination) escalation.202203```js204// Without `killDescendants`, only the shell is terminated, and `sleep` keeps running205const subprocess = execa({shell: true, killDescendants: true})`sleep 60`;206subprocess.kill();207await subprocess;208```209210On Unix, this spawns the subprocess in its own [process group](https://en.wikipedia.org/wiki/Process_group), then sends the signal to that group. On Windows, this uses [`taskkill`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill), which terminates the process tree tracked by the OS.211TweaksSindre Sorhusbefore adoption698a1b8
line 212why, one step back212This is best-effort. On Unix, descendant processes that create their own process group or session (for example, daemons calling [`setsid()`](https://man7.org/linux/man-pages/man2/setsid.2.html)) escape termination. On Unix, because the subprocess runs in its own process group, it is also detached from the terminal, so pressing `CTRL-C` no longer forwards [`SIGINT`](#sigint) to it. Finally, the OS can re-assign the subprocess' PID to an unrelated process once it is not used anymore. On Unix, this only happens once every process in its group exited, so calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) at that point might, in rare cases, signal an unrelated process group. On Windows, this happens as soon as the subprocess exited, so descendants are not signaled anymore at that point, which also prevents the [`forceKillAfterDelay`](#forceful-termination) escalation from terminating them.Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec
lines 213–214why, one step back213214This option cannot be used with [synchronous methods](execution.md#synchronous-execution).Document Windows subprocess tree cleanup workaround (#1250)Sindre Sorhusbefore adoption97dc613
line 215why, one step back215100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 216–223why, one step back216## Signal termination217218[`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.219220[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)221222### SIGTERM223Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 224why, one step back224[`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.100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 225–232why, one step back225226```js227const subprocess = execa`npm run build`;228subprocess.kill();229// Is the same as:230subprocess.kill('SIGTERM');231```232Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 233why, one step back233### SIGINT100% test coverage (#1018)ehmickybefore adoption9f65b86
line 234why, one step back234Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
lines 235–236why, one step back235[`SIGINT`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGINT) terminates the process. Its [handler](#handling-signals) is triggered on `CTRL-C`.236100% test coverage (#1018)ehmickybefore adoption9f65b86
line 237why, one step back237```jsImprove documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 238why, one step back238subprocess.kill('SIGINT');100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 239–242why, one step back239```240241### SIGKILL242Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 243why, one step back243[`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL) forcefully terminates the subprocess. It [cannot be handled](#handling-signals).100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 244–248why, one step back244245```js246subprocess.kill('SIGKILL');247```248Document `SIGQUIT` (#1022)ehmickybefore adoptionc5bd9d8
lines 249–250why, one step back249### SIGQUIT250Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 251why, one step back251[`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 252–256why, one step back252253```js254subprocess.kill('SIGQUIT');255```256100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 257–268why, one step back257### Other signals258259Other 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).260261### Default signal262263The [`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.264265```js266const subprocess = execa({killSignal: 'SIGKILL'})`npm run build`;267subprocess.kill(); // Forceful termination268```Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
lines 269–281why, one step back269270### Handling signals271272On Unix, most signals (not [`SIGKILL`](#sigkill)) can be intercepted to perform a graceful exit.273274```js275process.on('SIGTERM', () => {276 cleanup();277 process.exit(1);278})279```280281Unfortunately 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 282–283why, one step back282283Execa provides the [`gracefulCancel`](#graceful-termination) option as a cross-platform alternative to signal handlers.100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 284–309why, one step back284285### Signal name and description286287When a subprocess was terminated by a signal, [`error.isTerminated`](api.md#erroristerminated) is `true`.288289Also, [`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).290291```js292try {293 await execa`npm run build`;294} catch (error) {295 if (error.isTerminated) {296 console.error(error.signal); // SIGFPE297 console.error(error.signalDescription); // 'Floating point arithmetic error'298 }299300 throw error;301}302```303304## Forceful termination305306If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.307308The grace period is set by the [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option, which is 5 seconds by default. This feature can be disabled with `false`.309Add `error.isForcefullyTerminated` (#1111)ehmickybefore adoptione69985d
lines 310–311why, one step back310The [`error.isForcefullyTerminated`](api.md#errorisforcefullyterminated) boolean property can be used to check whether a subprocess was forcefully terminated by the `forceKillAfterDelay` option.311100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 312–379why, one step back312This works when the subprocess is terminated by either:313- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with no arguments.314- The [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) or [`cleanup`](#current-process-exit) option.315316This does not work when the subprocess is terminated by either:317- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with a specific signal.318- Calling [`process.kill(subprocess.pid)`](api.md#subprocesspid).319- Sending a termination signal [from another process](#inter-process-termination).320321Also, 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.322323```js324// No forceful termination325const subprocess = execa({forceKillAfterDelay: false})`npm run build`;326subprocess.kill();327```328329## Inter-process termination330331[`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.332333```js334const subprocess = execa`npm run build`;335console.log('PID:', subprocess.pid); // PID: 6513336await subprocess;337```338339For example, from a terminal:340341```sh342$ kill -SIGTERM 6513343```344345Or from a different Node.js process:346347```js348import process from 'node:process';349350process.kill(subprocessPid);351```352353## Error message and stack trace354355When 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).356357```js358try {359 const subprocess = execa`npm run build`;360 setTimeout(() => {361 subprocess.kill(new Error('Timed out after 5 seconds.'));362 }, 5000);363 await subprocess;364} catch (error) {365 if (error.isTerminated) {366 console.error(error.cause); // new Error('Timed out after 5 seconds.')367 console.error(error.cause.stack); // Stack trace from `error.cause`368 console.error(error.originalMessage); // 'Timed out after 5 seconds.'369 }370371 throw error;372}373```374375<hr>376377[**Next**: 🎹 Input](input.md)\378[**Previous**: ❌ Errors](errors.md)\379[**Top**: Table of contents](../readme.md#documentation)