Skip to content
Myr

termination.md

This file

Path

docs/termination.md

360 lines · 13.7 KiB · Markdown

Last changed by

Document Windows subprocess tree cleanup workaround (#1250)Sindre Sorhusbefore adoption97dc613

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

Document Windows subprocess tree cleanup workaround (#1250)Sindre Sorhusbefore adoption97dc613

lines 195–196why, one step back
195On Windows, only the subprocess is terminated, not the other processes it might have spawned. To also terminate those, the [`windowsHide: false`](windows.md#console-window) option can be used.
196

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 197–198why, one step back
197## Signal termination
198

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

line 199why, one step back
199[`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 200–204why, one step back
200
201[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)202203### SIGTERM204

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 205why, one step back
205[`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 206–213why, one step back
206
207```js208const subprocess = execa`npm run build`;209subprocess.kill();210// Is the same as:211subprocess.kill('SIGTERM');212```213

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 215why, one step back
215

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 220–223why, one step back
220```
221222### SIGKILL223

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 224why, one step back
224[`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 225–229why, one step back
225
226```js227subprocess.kill('SIGKILL');228```229

Document `SIGQUIT` (#1022)ehmickybefore adoptionc5bd9d8

lines 230–231why, one step back
230### SIGQUIT
231

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 232why, one step back
232[`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 233–237why, one step back
233
234```js235subprocess.kill('SIGQUIT');236```237

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 238–243why, one step back
238### Other signals
239240Other 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).241242### Default signal243

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

line 244why, one step back
244The [`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 245–249why, one step back
245
246```js247const subprocess = execa({killSignal: 'SIGKILL'})`npm run build`;248subprocess.kill(); // Forceful termination249```

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

lines 250–262why, one step back
250
251### Handling signals252253On Unix, most signals (not [`SIGKILL`](#sigkill)) can be intercepted to perform a graceful exit.254255```js256process.on('SIGTERM', () => {257 cleanup();258 process.exit(1);259})260```261262Unfortunately 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 263–264why, one step back
263
264Execa provides the [`gracefulCancel`](#graceful-termination) option as a cross-platform alternative to signal handlers.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 265–267why, one step back
265
266### Signal name and description267

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 269why, one step back
269

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

line 270why, one step back
270Also, [`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 271–288why, one step back
271
272```js273try {274 await execa`npm run build`;275} catch (error) {276 if (error.isTerminated) {277 console.error(error.signal); // SIGFPE278 console.error(error.signalDescription); // 'Floating point arithmetic error'279 }280281 throw error;282}283```284285## Forceful termination286287If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.288

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

line 289why, one step back
289The 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 290why, one step back
290

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 295–297why, one step back
295- The [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) or [`cleanup`](#current-process-exit) option.
296297This does not work when the subprocess is terminated by either:

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 300–311why, one step back
300- Sending a termination signal [from another process](#inter-process-termination).
301302Also, 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.303304```js305// No forceful termination306const subprocess = execa({forceKillAfterDelay: false})`npm run build`;307subprocess.kill();308```309310## Inter-process termination311

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

line 312why, one step back
312[`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 313–319why, one step back
313
314```js315const subprocess = execa`npm run build`;316console.log('PID:', subprocess.pid); // PID: 6513317await subprocess;318```319

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

lines 320–321why, one step back
320For example, from a terminal:
321

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 322–323why, one step back
322```sh
323$ kill -SIGTERM 6513

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

lines 324–331why, one step back
324```
325326Or from a different Node.js process:327328```js329import process from 'node:process';330331process.kill(subprocessPid);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 332–335why, one step back
332```
333334## Error message and stack trace335

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

line 336why, one step back
336When 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 337–360why, one step back
337
338```js339try {340 const subprocess = execa`npm run build`;341 setTimeout(() => {342 subprocess.kill(new Error('Timed out after 5 seconds.'));343 }, 5000);344 await subprocess;345} catch (error) {346 if (error.isTerminated) {347 console.error(error.cause); // new Error('Timed out after 5 seconds.')348 console.error(error.cause.stack); // Stack trace from `error.cause`349 console.error(error.originalMessage); // 'Timed out after 5 seconds.'350 }351352 throw error;353}354```355356<hr>357358[**Next**: 🎹 Input](input.md)\359[**Previous**: ❌ Errors](errors.md)\360[**Top**: Table of contents](../readme.md#documentation)