Commit 020cb3ce4e1 for nodejs
commit 020cb3ce4e10989b6a98c756993b1bb26ddf9e77
Author: Guilherme Araújo <arauujogui@gmail.com>
Date: Tue Dec 1 18:38:03 2026 -0300
src: forward signals to node --run scripts
Forward SIGINT and SIGTERM to the script and wait for it to exit, like
`npm run`. Exit with the script's exit code, or re-raise the signal
that terminated it, instead of reporting failures as 1 and signal
deaths as success.
Refs: https://github.com/nodejs/node/issues/65712
Assisted-by: Claude Code
Signed-off-by: Guilherme Araújo <arauujogui@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67736
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Daniel Lemire <daniel@lemire.me>
diff --git a/doc/api/cli.md b/doc/api/cli.md
index 570e2bec36c..293c5286aa6 100644
--- a/doc/api/cli.md
+++ b/doc/api/cli.md
@@ -3081,6 +3081,9 @@ forked processes, or clustered processes.
<!-- YAML
added: v22.0.0
changes:
+ - version: REPLACEME
+ pr-url: https://github.com/nodejs/node/pull/67736
+ description: Forwards signals to the script and propagates its exit status.
- version:
- v26.9.0
- v24.22.0
@@ -3159,6 +3162,21 @@ The following environment variables are set when running a script with `--run`:
Environment variables loaded from a file with [`--env-file`][] are not applied
to the command executed by `--run`.
+#### Signals and exit codes
+
+`node --run` exits with the exit code of the script, or with the signal that
+terminated it. If the script was terminated by a signal whose default action
+dumps core (such as `SIGSEGV` or `SIGABRT`), `node --run` instead exits with
+code 128 plus the signal number.
+
+On POSIX, `node --run` forwards `SIGINT`, `SIGTERM`, `SIGHUP`, and `SIGQUIT`
+to the script and waits for it to exit. In a terminal, <kbd>Ctrl</kbd>+<kbd>C</kbd> already reaches the script, so `node --run` does
+not forward it a second time.
+
+The script runs in a shell, which forwarded signals reach. For a compound
+command such as `build && start`, the signal may not reach `start`. Use `exec`
+(`build && exec start`) so that it does.
+
### `--secure-heap-min=n`
<!-- YAML
diff --git a/src/node_task_runner.cc b/src/node_task_runner.cc
index b9716846abf..7449a1d2dc1 100644
--- a/src/node_task_runner.cc
+++ b/src/node_task_runner.cc
@@ -4,6 +4,11 @@
#include <regex> // NOLINT(build/c++11)
+#ifndef _WIN32
+#include <fcntl.h>
+#include <unistd.h>
+#endif // _WIN32
+
namespace node::task_runner {
#ifdef _WIN32
@@ -199,26 +204,147 @@ void ProcessRunner::ExitCallback(uv_process_t* handle,
int term_signal) {
const auto self = static_cast<ProcessRunner*>(handle->data);
uv_close(reinterpret_cast<uv_handle_t*>(handle), nullptr);
+#ifndef _WIN32
+ self->StopForwardingSignals();
+#endif // _WIN32
self->OnExit(exit_status, term_signal);
}
void ProcessRunner::OnExit(int64_t exit_status, int term_signal) {
- if (exit_status > 0) {
- init_result_->exit_code_ = ExitCode::kGenericUserError;
+ if (term_signal != 0) {
+ // Fallback if the signal can't be re-raised.
+ term_signal_ = term_signal;
+ init_result_->exit_code_ = static_cast<ExitCode>(128 + term_signal);
} else {
- init_result_->exit_code_ = ExitCode::kNoFailure;
+ init_result_->exit_code_ = static_cast<ExitCode>(exit_status);
+ }
+}
+
+#ifndef _WIN32
+// Signals that a terminal sends to its whole foreground process group.
+static bool IsTerminalGeneratedSignal(int signum) {
+ return signum == SIGINT || signum == SIGQUIT || signum == SIGHUP;
+}
+
+// Whether the runner is in the foreground process group of its controlling
+// terminal. The script inherits that process group.
+static bool IsInTerminalForegroundGroup() {
+ const pid_t group = getpgrp();
+ for (int fd = 0; fd <= 2; fd++) {
+ // Fails if the fd is not the controlling terminal.
+ const pid_t foreground = tcgetpgrp(fd);
+ if (foreground != -1) return foreground == group;
+ }
+ // The stdio may be redirected while a controlling terminal exists.
+ const int fd = open("/dev/tty", O_RDONLY | O_NOCTTY | O_CLOEXEC);
+ if (fd == -1) return false;
+ const pid_t foreground = tcgetpgrp(fd);
+ close(fd);
+ return foreground == group;
+}
+
+void ProcessRunner::SignalCallback(uv_signal_t* handle, int signum) {
+ const auto self = static_cast<ProcessRunner*>(handle->data);
+ // The terminal has already sent this signal to the script (e.g. Ctrl+C).
+ // Forwarding it would deliver it twice.
+ if (IsTerminalGeneratedSignal(signum) && IsInTerminalForegroundGroup()) {
+ return;
+ }
+ USE(uv_process_kill(&self->process_, signum));
+}
+
+void ProcessRunner::StartForwardingSignals() {
+ for (size_t i = 0; i < std::size(kForwardedSignals); i++) {
+ CHECK_EQ(sigaction(kForwardedSignals[i], nullptr, &previous_actions_[i]),
+ 0);
+ uv_signal_t* signal_handle = &signal_handles_[i];
+ CHECK_EQ(uv_signal_init(loop_, signal_handle), 0);
+ signal_handle->data = this;
+ CHECK_EQ(
+ uv_signal_start(signal_handle, SignalCallback, kForwardedSignals[i]),
+ 0);
+ }
+}
+
+void ProcessRunner::StopForwardingSignals() {
+ // Block the signals so none arrives while uv_close leaves them SIG_DFL.
+ sigset_t forwarded;
+ sigset_t previous_mask;
+ sigemptyset(&forwarded);
+ for (int signum : kForwardedSignals) sigaddset(&forwarded, signum);
+ CHECK_EQ(pthread_sigmask(SIG_BLOCK, &forwarded, &previous_mask), 0);
+ for (size_t i = 0; i < std::size(kForwardedSignals); i++) {
+ uv_close(reinterpret_cast<uv_handle_t*>(&signal_handles_[i]), nullptr);
+ // Not necessarily SignalExit, e.g. with kNoDefaultSignalHandling.
+ CHECK_EQ(sigaction(kForwardedSignals[i], &previous_actions_[i], nullptr),
+ 0);
+ }
+ CHECK_EQ(pthread_sigmask(SIG_SETMASK, &previous_mask, nullptr), 0);
+}
+
+// Re-raising these would make the runner dump core too.
+static bool IsCoreDumpSignal(int signum) {
+ switch (signum) {
+ case SIGABRT:
+ case SIGBUS:
+ case SIGFPE:
+ case SIGILL:
+ case SIGQUIT:
+ case SIGSEGV:
+ case SIGSYS:
+ case SIGTRAP:
+ case SIGXCPU:
+ case SIGXFSZ:
+ return true;
+ default:
+ return false;
+ }
+}
+
+// Exit with the same signal as the child.
+static void ReraiseSignal(int signum) {
+ ResetStdio(true);
+
+ // SIGKILL and SIGSTOP can't be caught, so they're always SIG_DFL.
+ if (signum != SIGKILL && signum != SIGSTOP) {
+ struct sigaction sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sa_handler = SIG_DFL;
+ CHECK_EQ(sigaction(signum, &sa, nullptr), 0);
}
+
+ sigset_t sigmask;
+ sigemptyset(&sigmask);
+ sigaddset(&sigmask, signum);
+ CHECK_EQ(pthread_sigmask(SIG_UNBLOCK, &sigmask, nullptr), 0);
+
+ raise(signum);
}
+#endif // _WIN32
void ProcessRunner::Run() {
// keeps the string alive until destructor
cwd_ = ConvertPathToUTF8(package_json_path_.parent_path());
options_.cwd = cwd_.c_str();
+#ifndef _WIN32
+ // Stopped in ExitCallback.
+ StartForwardingSignals();
+#endif // _WIN32
if (int r = uv_spawn(loop_, &process_, &options_)) {
fprintf(stderr, "Error: %s\n", uv_strerror(r));
+ init_result_->exit_code_ = ExitCode::kGenericUserError;
+#ifndef _WIN32
+ StopForwardingSignals();
+#endif // _WIN32
}
uv_run(loop_, UV_RUN_DEFAULT);
+
+#ifndef _WIN32
+ if (term_signal_ != 0 && !IsCoreDumpSignal(term_signal_)) {
+ ReraiseSignal(term_signal_);
+ }
+#endif // _WIN32
}
std::optional<std::tuple<std::filesystem::path, std::string, std::string>>
diff --git a/src/node_task_runner.h b/src/node_task_runner.h
index 8cdfe572353..733801ecd5b 100644
--- a/src/node_task_runner.h
+++ b/src/node_task_runner.h
@@ -7,7 +7,9 @@
#include "spawn_sync.h"
#include "uv.h"
+#include <csignal>
#include <filesystem>
+#include <iterator>
#include <optional>
#include <string_view>
#include <tuple>
@@ -44,6 +46,19 @@ class ProcessRunner {
std::unique_ptr<char* []> env_ {}; // memory for options_.env
std::unique_ptr<char* []> arg_ {}; // memory for options_.args
std::string cwd_;
+ // Signal that killed the child, or 0.
+ int term_signal_ = 0;
+
+#ifndef _WIN32
+ // Forwarded to the child, like npm.
+ static constexpr int kForwardedSignals[] = {SIGINT, SIGTERM, SIGHUP, SIGQUIT};
+ uv_signal_t signal_handles_[std::size(kForwardedSignals)]{};
+ struct sigaction previous_actions_[std::size(kForwardedSignals)]{};
+
+ static void SignalCallback(uv_signal_t* handle, int signum);
+ void StartForwardingSignals();
+ void StopForwardingSignals();
+#endif // _WIN32
// OnExit is the callback function that is called when the process exits.
void OnExit(int64_t exit_status, int term_signal);
diff --git a/test/parallel/test-node-run-signals.js b/test/parallel/test-node-run-signals.js
new file mode 100644
index 00000000000..e1a26ceb7ca
--- /dev/null
+++ b/test/parallel/test-node-run-signals.js
@@ -0,0 +1,131 @@
+'use strict';
+
+const common = require('../common');
+const assert = require('node:assert');
+const { spawn } = require('node:child_process');
+const { once } = require('node:events');
+const fs = require('node:fs');
+const os = require('node:os');
+const { describe, it } = require('node:test');
+
+const tmpdir = require('../common/tmpdir');
+
+tmpdir.refresh();
+
+// Passed via the env, as the path may contain shell metacharacters.
+const env = { ...process.env, NODE: process.execPath };
+const forwardedSignals = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'];
+
+fs.writeFileSync(tmpdir.resolve('handle-signals.js'), `
+const timer = setInterval(() => {}, 1000);
+for (const signal of ${JSON.stringify(forwardedSignals)}) {
+ process.on(signal, () => {
+ console.log('received ' + signal);
+ process.exitCode = 7;
+ clearInterval(timer);
+ });
+}
+console.log('ready', process.pid);
+`);
+
+fs.writeFileSync(tmpdir.resolve('package.json'), JSON.stringify({
+ scripts: {
+ 'exit-code': 'exit 42',
+ 'self-terminate': 'kill -TERM $$',
+ 'self-kill': 'kill -KILL $$',
+ 'self-abort': 'ulimit -c 0; kill -ABRT $$',
+ // `exec` so signals reach node, not the shell.
+ 'handle-signals': 'exec "$NODE" handle-signals.js',
+ 'no-signal-handlers':
+ `exec "$NODE" -e "console.log('ready', process.pid); setInterval(() => {}, 1000)"`,
+ },
+}));
+
+function run(script) {
+ return common.spawnPromisified(process.execPath, ['--run', script], {
+ cwd: tmpdir.path,
+ env,
+ });
+}
+
+// Sends `signal` to the runner once the script is ready.
+async function runAndSignal(script, signal) {
+ const child = spawn(process.execPath, ['--run', script], {
+ cwd: tmpdir.path,
+ env,
+ stdio: ['ignore', 'pipe', 'inherit'],
+ // No controlling terminal, so all signals are forwarded.
+ detached: true,
+ });
+ const exited = once(child, 'exit');
+ const closed = once(child, 'close');
+ let stdout = '';
+ let scriptPid;
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk) => {
+ stdout += chunk;
+ const ready = scriptPid === undefined && /^ready (\d+)\n/.exec(stdout);
+ if (ready) {
+ scriptPid = Number(ready[1]);
+ child.kill(signal);
+ }
+ });
+ const [code, exitSignal] = await exited;
+ // Don't leak the script if the runner didn't wait for it.
+ if (scriptPid !== undefined) {
+ try {
+ process.kill(scriptPid, 'SIGKILL');
+ } catch {
+ // Already exited.
+ }
+ }
+ await closed;
+ return { code, signal: exitSignal, stdout };
+}
+
+describe('node --run exit codes', () => {
+ it('uses the exit code of the script', async () => {
+ const child = await run('exit-code');
+ assert.strictEqual(child.code, 42);
+ assert.strictEqual(child.signal, null);
+ });
+});
+
+describe('node --run signal handling', {
+ skip: common.isWindows && 'POSIX signals are not supported on Windows',
+}, () => {
+ it('terminates with the signal that terminated the script', async () => {
+ const child = await run('self-terminate');
+ assert.strictEqual(child.code, null);
+ assert.strictEqual(child.signal, 'SIGTERM');
+ });
+
+ it('terminates with SIGKILL if the script was killed', async () => {
+ const child = await run('self-kill');
+ assert.strictEqual(child.code, null);
+ assert.strictEqual(child.signal, 'SIGKILL');
+ });
+
+ it('exits with 128 + signal instead of re-raising a core-dumping signal',
+ async () => {
+ const child = await run('self-abort');
+ assert.strictEqual(child.code, 128 + os.constants.signals.SIGABRT);
+ assert.strictEqual(child.signal, null);
+ });
+
+ for (const signal of forwardedSignals) {
+ it(`forwards ${signal} and waits for the script to exit`, async () => {
+ const child = await runAndSignal('handle-signals', signal);
+ assert.match(child.stdout, new RegExp(`^ready \\d+\\nreceived ${signal}\\n$`));
+ assert.strictEqual(child.code, 7);
+ assert.strictEqual(child.signal, null);
+ });
+ }
+
+ it('terminates with a forwarded signal the script does not handle',
+ async () => {
+ const child = await runAndSignal('no-signal-handlers', 'SIGTERM');
+ assert.strictEqual(child.code, null);
+ assert.strictEqual(child.signal, 'SIGTERM');
+ });
+});