Skip to content
Myr

termination.md

This file

Path

docs/termination.md

210 lines · 7.4 KiB · Markdown

Last changed by

Document alternatives to process termination (#1026)ehmickybefore adoption9d7eed8

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–96why, one step back
66
67[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)6869### SIGTERM7071[`SIGTERM`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGTERM) is the default signal. It terminates the subprocess.7273```js74const subprocess = execa`npm run build`;75subprocess.kill();76// Is the same as:77subprocess.kill('SIGTERM');78```7980The subprocess can [handle that signal](https://nodejs.org/api/process.html#process_signal_events) to run some cleanup logic.8182```js83process.on('SIGTERM', () => {84 cleanup();85 process.exit(1);86})87```8889### SIGKILL9091[`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL) is like [`SIGTERM`](#sigterm) except it forcefully terminates the subprocess, i.e. it does not allow it to handle the signal.9293```js94subprocess.kill('SIGKILL');95```96

Document `SIGQUIT` (#1022)ehmickybefore adoptionc5bd9d8

lines 97–104why, one step back
97### SIGQUIT
9899[`SIGQUIT`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGQUIT) is like [`SIGTERM`](#sigterm) except it creates a [core dump](https://en.wikipedia.org/wiki/Core_dump).100101```js102subprocess.kill('SIGQUIT');103```104

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 105–110why, one step back
105### Other signals
106107Other 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).108109### Default signal110

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

line 111why, one step back
111The [`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 112–119why, one step back
112
113```js114const subprocess = execa({killSignal: 'SIGKILL'})`npm run build`;115subprocess.kill(); // Forceful termination116```117118### Signal name and description119

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 121why, one step back
121

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

line 122why, one step back
122Also, [`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 123–140why, one step back
123
124```js125try {126 await execa`npm run build`;127} catch (error) {128 if (error.isTerminated) {129 console.error(error.signal); // SIGFPE130 console.error(error.signalDescription); // 'Floating point arithmetic error'131 }132133 throw error;134}135```136137## Forceful termination138139If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.140

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

line 141why, one step back
141The 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 142–143why, one step back
142
143This works when the subprocess is terminated by either:

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 150–161why, one step back
150- Sending a termination signal [from another process](#inter-process-termination).
151152Also, 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.153154```js155// No forceful termination156const subprocess = execa({forceKillAfterDelay: false})`npm run build`;157subprocess.kill();158```159160## Inter-process termination161

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

line 162why, one step back
162[`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 163–169why, one step back
163
164```js165const subprocess = execa`npm run build`;166console.log('PID:', subprocess.pid); // PID: 6513167await subprocess;168```169

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

lines 170–171why, one step back
170For example, from a terminal:
171

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 172–173why, one step back
172```sh
173$ kill -SIGTERM 6513

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

lines 174–181why, one step back
174```
175176Or from a different Node.js process:177178```js179import process from 'node:process';180181process.kill(subprocessPid);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 182–185why, one step back
182```
183184## Error message and stack trace185

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

line 186why, one step back
186When 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 187–210why, one step back
187
188```js189try {190 const subprocess = execa`npm run build`;191 setTimeout(() => {192 subprocess.kill(new Error('Timed out after 5 seconds.'));193 }, 5000);194 await subprocess;195} catch (error) {196 if (error.isTerminated) {197 console.error(error.cause); // new Error('Timed out after 5 seconds.')198 console.error(error.cause.stack); // Stack trace from `error.cause`199 console.error(error.originalMessage); // 'Timed out after 5 seconds.'200 }201202 throw error;203}204```205206<hr>207208[**Next**: 🎹 Input](input.md)\209[**Previous**: ❌ Errors](errors.md)\210[**Top**: Table of contents](../readme.md#documentation)