Skip to content
Myr

termination.md

This file

Path

docs/termination.md

224 lines · 8.2 KiB · Markdown

Last changed by

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

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–15why, one step back
9## Alternatives
1011Terminating a subprocess ends it abruptly. This prevents rolling back the subprocess' operations and leaves them incomplete. When possible, graceful exits should be preferred, such as:12- Letting the subprocess end on its own.13- [Performing cleanup](#sigterm) in termination [signal handlers](https://nodejs.org/api/process.html#process_signal_events).14- [Sending a message](ipc.md) to the subprocess so it aborts its operations and cleans up.15

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

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

line 18why, one step back
18The [`cancelSignal`](api.md#optionscancelsignal) option can be used to cancel a subprocess. When [`abortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) 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 19–41why, one step back
19
20```js21import {execa} from 'execa';2223const abortController = new AbortController();2425setTimeout(() => {26 abortController.abort();27}, 5000);2829try {30 await execa({cancelSignal: abortController.signal})`npm run build`;31} catch (error) {32 if (error.isCanceled) {33 console.error('Aborted by cancelSignal.');34 }3536 throw error;37}38```3940## Timeout41

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

line 42why, one step back
42If 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 43–58why, one step back
43
44```js45try {46 await execa({timeout: 5000})`npm run build`;47} catch (error) {48 if (error.timedOut) {49 console.error('Timed out.');50 }5152 throw error;53}54```5556## Current process exit5758If the current process exits, the subprocess is automatically [terminated](#default-signal) unless either:

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

lines 59–60why, one step back
59- The [`cleanup`](api.md#optionscleanup) option is `false`.
60- The subprocess is run in the background using the [`detached`](api.md#optionsdetached) option.

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 61–64why, one step back
61- The current process was terminated abruptly, for example, with [`SIGKILL`](#sigkill) as opposed to [`SIGTERM`](#sigterm) or a successful exit.
6263## Signal termination64

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

line 65why, one step back
65[`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 66–70why, one step back
66
67[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)6869### SIGTERM70

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 71why, one step back
71[`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 72–79why, one step back
72
73```js74const subprocess = execa`npm run build`;75subprocess.kill();76// Is the same as:77subprocess.kill('SIGTERM');78```79

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 81why, one step back
81

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 86–89why, one step back
86```
8788### SIGKILL89

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 90why, one step back
90[`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 91–95why, one step back
91
92```js93subprocess.kill('SIGKILL');94```95

Document `SIGQUIT` (#1022)ehmickybefore adoptionc5bd9d8

lines 96–97why, one step back
96### SIGQUIT
97

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

line 98why, one step back
98[`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 99–103why, one step back
99
100```js101subprocess.kill('SIGQUIT');102```103

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 104–109why, one step back
104### Other signals
105106Other 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).107108### Default signal109

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

line 110why, one step back
110The [`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 111–115why, one step back
111
112```js113const subprocess = execa({killSignal: 'SIGKILL'})`npm run build`;114subprocess.kill(); // Forceful termination115```

Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42

lines 116–128why, one step back
116
117### Handling signals118119On Unix, most signals (not [`SIGKILL`](#sigkill)) can be intercepted to perform a graceful exit.120121```js122process.on('SIGTERM', () => {123 cleanup();124 process.exit(1);125})126```127128Unfortunately 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 user guides (#989)ehmickybefore adoptionbe91ecf

lines 129–131why, one step back
129
130### Signal name and description131

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 133why, one step back
133

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

line 134why, one step back
134Also, [`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 135–152why, one step back
135
136```js137try {138 await execa`npm run build`;139} catch (error) {140 if (error.isTerminated) {141 console.error(error.signal); // SIGFPE142 console.error(error.signalDescription); // 'Floating point arithmetic error'143 }144145 throw error;146}147```148149## Forceful termination150151If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.152

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

line 153why, one step back
153The 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 154why, one step back
154

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 164–175why, one step back
164- Sending a termination signal [from another process](#inter-process-termination).
165166Also, 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.167168```js169// No forceful termination170const subprocess = execa({forceKillAfterDelay: false})`npm run build`;171subprocess.kill();172```173174## Inter-process termination175

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

line 176why, one step back
176[`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 177–183why, one step back
177
178```js179const subprocess = execa`npm run build`;180console.log('PID:', subprocess.pid); // PID: 6513181await subprocess;182```183

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

lines 184–185why, one step back
184For example, from a terminal:
185

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 186–187why, one step back
186```sh
187$ kill -SIGTERM 6513

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

lines 188–195why, one step back
188```
189190Or from a different Node.js process:191192```js193import process from 'node:process';194195process.kill(subprocessPid);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 196–199why, one step back
196```
197198## Error message and stack trace199

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

line 200why, one step back
200When 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 201–224why, one step back
201
202```js203try {204 const subprocess = execa`npm run build`;205 setTimeout(() => {206 subprocess.kill(new Error('Timed out after 5 seconds.'));207 }, 5000);208 await subprocess;209} catch (error) {210 if (error.isTerminated) {211 console.error(error.cause); // new Error('Timed out after 5 seconds.')212 console.error(error.cause.stack); // Stack trace from `error.cause`213 console.error(error.originalMessage); // 'Timed out after 5 seconds.'214 }215216 throw error;217}218```219220<hr>221222[**Next**: 🎹 Input](input.md)\223[**Previous**: ❌ Errors](errors.md)\224[**Top**: Table of contents](../readme.md#documentation)