termination.md
This file
Path
docs/termination.md
222 lines · 8.0 KiB · Markdown
Last changed by
Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
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–15why, one step back9## Alternatives1011Terminating 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.15Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 16–17why, one step back16## Canceling17Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 18why, one step back18The [`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 back1920```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## Timeout41Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 42why, one step back42If 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 back4344```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 back59- 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 back61- The current process was terminated abruptly, for example, with [`SIGKILL`](#sigkill) as opposed to [`SIGTERM`](#sigterm) or a successful exit.6263## Signal termination64Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 65why, one step back65[`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 back6667[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)6869### SIGTERM70Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 71why, one step back71[`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 back7273```js74const subprocess = execa`npm run build`;75subprocess.kill();76// Is the same as:77subprocess.kill('SIGTERM');78```79Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 80why, one step back80### SIGINTAdd user guides (#989)ehmickybefore adoptionbe91ecf
line 81why, one step back81Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
lines 82–83why, one step back82[`SIGINT`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGINT) terminates the process. Its [handler](#handling-signals) is triggered on `CTRL-C`.83Add user guides (#989)ehmickybefore adoptionbe91ecf
line 84why, one step back84```jsImprove documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 85why, one step back85subprocess.kill('SIGINT');Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 86–89why, one step back86```8788### SIGKILL89Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 90why, one step back90[`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 back9192```js93subprocess.kill('SIGKILL');94```95Document `SIGQUIT` (#1022)ehmickybefore adoptionc5bd9d8
lines 96–97why, one step back96### SIGQUIT97Improve documentation of signal handling (#1105)ehmickybefore adoption01a4b42
line 98why, one step back98[`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 back99100```js101subprocess.kill('SIGQUIT');102```103Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 104–109why, one step back104### Other signals105106Other 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 signal109Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 110why, one step back110The [`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 back111112```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 back116117### 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 back129130### Signal name and description131Improve documentation of `error.*` fields (#1006)ehmickybefore adoption4ee0dec
line 132why, one step back132When a subprocess was terminated by a signal, [`error.isTerminated`](api.md#erroristerminated) is `true`.Add user guides (#989)ehmickybefore adoptionbe91ecf
line 133why, one step back133Improve documentation of `error.*` fields (#1006)ehmickybefore adoption4ee0dec
line 134why, one step back134Also, [`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 back135136```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.152Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 153why, one step back153The 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
lines 154–155why, one step back154155This works when the subprocess is terminated by either:Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 156why, one step back156- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with no arguments.Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 157–159why, one step back157- The [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) or [`cleanup`](#current-process-exit) option.158159This does not work when the subprocess is terminated by either:Move API reference to its own page (#996)ehmickybefore adoption7cde496
lines 160–161why, one step back160- Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with a specific signal.161- Calling [`process.kill(subprocess.pid)`](api.md#subprocesspid).Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 162–173why, one step back162- Sending a termination signal [from another process](#inter-process-termination).163164Also, 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.165166```js167// No forceful termination168const subprocess = execa({forceKillAfterDelay: false})`npm run build`;169subprocess.kill();170```171172## Inter-process termination173Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08
line 174why, one step back174[`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 175–181why, one step back175176```js177const subprocess = execa`npm run build`;178console.log('PID:', subprocess.pid); // PID: 6513179await subprocess;180```181Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08
lines 182–183why, one step back182For example, from a terminal:183Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 184–185why, one step back184```sh185$ kill -SIGTERM 6513Document `process.kill(subprocess.pid)` (#1005)ehmickybefore adoptionf8d4e08
lines 186–193why, one step back186```187188Or from a different Node.js process:189190```js191import process from 'node:process';192193process.kill(subprocessPid);Add user guides (#989)ehmickybefore adoptionbe91ecf
lines 194–197why, one step back194```195196## Error message and stack trace197Move API reference to its own page (#996)ehmickybefore adoption7cde496
line 198why, one step back198When 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 199–222why, one step back199200```js201try {202 const subprocess = execa`npm run build`;203 setTimeout(() => {204 subprocess.kill(new Error('Timed out after 5 seconds.'));205 }, 5000);206 await subprocess;207} catch (error) {208 if (error.isTerminated) {209 console.error(error.cause); // new Error('Timed out after 5 seconds.')210 console.error(error.cause.stack); // Stack trace from `error.cause`211 console.error(error.originalMessage); // 'Timed out after 5 seconds.'212 }213214 throw error;215}216```217218<hr>219220[**Next**: 🎹 Input](input.md)\221[**Previous**: ❌ Errors](errors.md)\222[**Top**: Table of contents](../readme.md#documentation)