Skip to content
Myr

termination.md

This file

Path

docs/termination.md

379 lines · 16.0 KiB · Markdown

Last changed by

TweaksSindre Sorhusbefore adoption698a1b8

History of this file

Take it

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1–8why, one step back
1<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# 🏁 Termination8

Document alternatives to process termination (#1026)ehmickybefore adoption9d7eed8

lines 9–10why, one step back
9## Alternatives
10

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

line 11why, one step back
11Terminating 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 back
12

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

lines 13–14why, one step back
13Ideally subprocesses should end on their own. If that's not possible, [graceful termination](#graceful-termination) should be preferred.
14

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 15–16why, one step back
15## Canceling
16

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

line 17why, one step back
17The [`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 back
18
19```js

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

line 20why, one step back
20import {execaNode} from 'execa';

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 21why, one step back
21

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

lines 22–23why, one step back
22const controller = new AbortController();
23const cancelSignal = controller.signal;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 24–25why, one step back
24
25setTimeout(() => {

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

line 26why, one step back
26 controller.abort();

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 27–29why, one step back
27}, 5000);
2829try {

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

line 30why, one step back
30 await execaNode({cancelSignal})`build.js`;

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 31–32why, one step back
31} catch (error) {
32 if (error.isCanceled) {

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

line 33why, one step back
33 console.error('Canceled by cancelSignal.');

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 34–39why, one step back
34 }
3536 throw error;37}38```39

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

lines 40–120why, one step back
40## Graceful termination
4142### 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```120

Require Node.js 22 (#1243)Sindre Sorhusbefore adoption04b4454

line 121why, one step back
121However, 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 back
122
123If 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.124

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 125–126why, one step back
125## Timeout
126

Document how to terminate hanging subprocesses (#1140)ehmickybefore adoptionc0b6efc

lines 127–128why, one step back
127### Execution timeout
128

Move API reference to its own page (#996)ehmickybefore adoption7cde496

line 129why, one step back
129If 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 back
130
131```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 back
141```
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 back
186```
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 back
191- 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–194why, one step back
193- The current process was terminated abruptly, for example, with [`SIGKILL`](#sigkill) as opposed to [`SIGTERM`](#sigterm) or a successful exit.
194

Add `killDescendants` option to also terminate descendant processes (#1256)Sindre Sorhusbefore adoption84fa0ec

lines 195–211why, one step back
195By 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.211

TweaksSindre Sorhusbefore adoption698a1b8

line 212why, one step back
212This 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 back
213
214This 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 back
215

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 216–217why, one step back
216## Signal termination
217

Move API reference to its own page (#996)ehmickybefore adoption7cde496

line 218why, one step back
218[`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 219–223why, one step back
219
220[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)221222### SIGTERM223

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 224why, one step back
224[`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 225–232why, one step back
225
226```js227const subprocess = execa`npm run build`;228subprocess.kill();229// Is the same as:230subprocess.kill('SIGTERM');231```232

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 233why, one step back
233### SIGINT

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 234why, one step back
234

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

lines 235–236why, one step back
235[`SIGINT`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGINT) terminates the process. Its [handler](#handling-signals) is triggered on `CTRL-C`.
236

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 237why, one step back
237```js

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 238why, one step back
238subprocess.kill('SIGINT');

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 239–242why, one step back
239```
240241### SIGKILL242

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 243why, one step back
243[`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 244–248why, one step back
244
245```js246subprocess.kill('SIGKILL');247```248

Document `SIGQUIT` (#1022)ehmickybefore adoptionc5bd9d8

lines 249–250why, one step back
249### SIGQUIT
250

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 251why, one step back
251[`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 back
252
253```js254subprocess.kill('SIGQUIT');255```256

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 257–262why, one step back
257### Other signals
258259Other 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 signal262

Move API reference to its own page (#996)ehmickybefore adoption7cde496

line 263why, one step back
263The [`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 264–268why, one step back
264
265```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 back
269
270### 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 back
282
283Execa provides the [`gracefulCancel`](#graceful-termination) option as a cross-platform alternative to signal handlers.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 284–286why, one step back
284
285### Signal name and description286

Improve documentation of `error.*` fields (#1006)ehmickybefore adoption4ee0dec

line 287why, one step back
287When a subprocess was terminated by a signal, [`error.isTerminated`](api.md#erroristerminated) is `true`.

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 288why, one step back
288

Improve documentation of `error.*` fields (#1006)ehmickybefore adoption4ee0dec

line 289why, one step back
289Also, [`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 290–307why, one step back
290
291```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.307

Move API reference to its own page (#996)ehmickybefore adoption7cde496

line 308why, one step back
308The 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 309why, one step back
309

Add `error.isForcefullyTerminated` (#1111)ehmickybefore adoptione69985d

lines 310–311why, one step back
310The [`error.isForcefullyTerminated`](api.md#errorisforcefullyterminated) boolean property can be used to check whether a subprocess was forcefully terminated by the `forceKillAfterDelay` option.
311

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 312why, one step back
312This works when the subprocess is terminated by either:

Move API reference to its own page (#996)ehmickybefore adoption7cde496

line 313why, one step back
313- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with no arguments.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 314–316why, one step back
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:

Move API reference to its own page (#996)ehmickybefore adoption7cde496

lines 317–318why, one step back
317- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with a specific signal.
318- Calling [`process.kill(subprocess.pid)`](api.md#subprocesspid).

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 319–330why, one step back
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 termination330

Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08

line 331why, one step back
331[`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 332–338why, one step back
332
333```js334const subprocess = execa`npm run build`;335console.log('PID:', subprocess.pid); // PID: 6513336await subprocess;337```338

Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08

lines 339–340why, one step back
339For example, from a terminal:
340

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 341–342why, one step back
341```sh
342$ kill -SIGTERM 6513

Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08

lines 343–350why, one step back
343```
344345Or from a different Node.js process:346347```js348import process from 'node:process';349350process.kill(subprocessPid);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 351–354why, one step back
351```
352353## Error message and stack trace354

Move API reference to its own page (#996)ehmickybefore adoption7cde496

line 355why, one step back
355When 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 356–379why, one step back
356
357```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)