Skip to content
Myr

termination.md

This file

Path

docs/termination.md

195 lines · 6.8 KiB · Markdown

Last changed by

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

History of this file

Take it

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 1–10why, 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# 🏁 Termination89## Canceling10

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

line 11why, one step back
11The [`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 12–34why, one step back
12
13```js14import {execa} from 'execa';1516const abortController = new AbortController();1718setTimeout(() => {19 abortController.abort();20}, 5000);2122try {23 await execa({cancelSignal: abortController.signal})`npm run build`;24} catch (error) {25 if (error.isCanceled) {26 console.error('Aborted by cancelSignal.');27 }2829 throw error;30}31```3233## Timeout34

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

line 35why, one step back
35If 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 36–51why, one step back
36
37```js38try {39 await execa({timeout: 5000})`npm run build`;40} catch (error) {41 if (error.timedOut) {42 console.error('Timed out.');43 }4445 throw error;46}47```4849## Current process exit5051If the current process exits, the subprocess is automatically [terminated](#default-signal) unless either:

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

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

line 58why, one step back
58[`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 59–95why, one step back
59
60[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)6162### SIGTERM6364[`SIGTERM`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGTERM) is the default signal. It terminates the subprocess.6566```js67const subprocess = execa`npm run build`;68subprocess.kill();69// Is the same as:70subprocess.kill('SIGTERM');71```7273The subprocess can [handle that signal](https://nodejs.org/api/process.html#process_signal_events) to run some cleanup logic.7475```js76process.on('SIGTERM', () => {77 cleanup();78 process.exit(1);79})80```8182### SIGKILL8384[`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.8586```js87subprocess.kill('SIGKILL');88```8990### Other signals9192Other 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).9394### Default signal95

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

line 96why, one step back
96The [`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 97–104why, one step back
97
98```js99const subprocess = execa({killSignal: 'SIGKILL'})`npm run build`;100subprocess.kill(); // Forceful termination101```102103### Signal name and description104

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

line 106why, one step back
106

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

line 107why, one step back
107Also, [`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 108–125why, one step back
108
109```js110try {111 await execa`npm run build`;112} catch (error) {113 if (error.isTerminated) {114 console.error(error.signal); // SIGFPE115 console.error(error.signalDescription); // 'Floating point arithmetic error'116 }117118 throw error;119}120```121122## Forceful termination123124If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.125

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

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

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

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

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

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

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 135–146why, one step back
135- Sending a termination signal [from another process](#inter-process-termination).
136137Also, 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.138139```js140// No forceful termination141const subprocess = execa({forceKillAfterDelay: false})`npm run build`;142subprocess.kill();143```144145## Inter-process termination146

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

line 147why, one step back
147[`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 148–154why, one step back
148
149```js150const subprocess = execa`npm run build`;151console.log('PID:', subprocess.pid); // PID: 6513152await subprocess;153```154

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

lines 155–156why, one step back
155For example, from a terminal:
156

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 157–158why, one step back
157```sh
158$ kill -SIGTERM 6513

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

lines 159–166why, one step back
159```
160161Or from a different Node.js process:162163```js164import process from 'node:process';165166process.kill(subprocessPid);

Add user guides (#989)ehmickybefore adoptionbe91ecf

lines 167–170why, one step back
167```
168169## Error message and stack trace170

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

line 171why, one step back
171When 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 172–195why, one step back
172
173```js174try {175 const subprocess = execa`npm run build`;176 setTimeout(() => {177 subprocess.kill(new Error('Timed out after 5 seconds.'));178 }, 5000);179 await subprocess;180} catch (error) {181 if (error.isTerminated) {182 console.error(error.cause); // new Error('Timed out after 5 seconds.')183 console.error(error.cause.stack); // Stack trace from `error.cause`184 console.error(error.originalMessage); // 'Timed out after 5 seconds.'185 }186187 throw error;188}189```190191<hr>192193[**Next**: 🎹 Input](input.md)\194[**Previous**: ❌ Errors](errors.md)\195[**Top**: Table of contents](../readme.md#documentation)