From 8622c23ebc7707d008b15b119d0dabb307c8732c Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Sat, 21 Nov 2026 14:14:14 +0800 Subject: [PATCH] fix(cli): forward SIGTERM and SIGHUP from vp wrappers to the child Global `vp dev` runs the Rust `vp`, `node dist/bin.js`, and Vite. A SIGTERM to the `vp` process ID stopped only `vp`, and Vite kept the port open. `execute_with_terminal_guard` now forwards SIGTERM and SIGHUP to the child while the child runs. Both wrappers use this function, so the signal passes through `dist/bin.js` to Vite. SIGINT is still not forwarded, because the terminal sends Ctrl+C to the whole process group. A signal that the caller ignores stays ignored. Refs #3106. Co-Authored-By: Claude Opus 5.5 --- .../command_dev_local_signal/probe.mjs | 15 +++- .../command_dev_local_signal/snapshots.toml | 7 ++ .../snapshots/command_dev_global_signal.md | 10 +++ crates/vp_command/src/lib.rs | 7 +- crates/vp_command/src/signal_forward.rs | 73 +++++++++++++++++++ 5 files changed, 107 insertions(+), 5 deletions(-) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/snapshots/command_dev_global_signal.md create mode 100644 crates/vp_command/src/signal_forward.rs diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/probe.mjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/probe.mjs index 6aec3c9050..3d25dcaf8e 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/probe.mjs +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/probe.mjs @@ -8,6 +8,9 @@ import { join } from 'node:path'; import { createInterface } from 'node:readline'; const workerMode = process.argv[2] === '--worker'; +// The global vp runs `dist/bin.js`, which keeps Vite in a child process. +const globalMode = process.argv[2] === '--global'; +const localMode = !workerMode && !globalMode; async function listenerInfo(stdout, launchPid) { let listener; @@ -15,6 +18,10 @@ async function listenerInfo(stdout, launchPid) { const match = /^listening (\d+) (\d+)$/.exec(line); if (match) { listener = { port: Number(match[1]), pid: Number(match[2]) }; + if (globalMode) { + assert.notEqual(listener.pid, launchPid, 'Vite runs below the global vp process'); + return listener; + } if (!workerMode) { assert.equal(listener.pid, launchPid); return listener; @@ -32,7 +39,7 @@ const cache = mkdtempSync(join(tmpdir(), 'vp-dev-cache-')); const cacheProof = join(cache, 'cache-before-vite'); const env = { ...process.env, NODE_COMPILE_CACHE: cache }; delete env.NODE_DISABLE_COMPILE_CACHE; -if (!workerMode) { +if (localMode) { env.NODE_OPTIONS = ['--require=./check-launcher-cache.cjs', env.NODE_OPTIONS] .filter(Boolean) .join(' '); @@ -57,7 +64,7 @@ try { console.log('Vite served the project with the client under /probe/'); if (workerMode) { console.log('The Worker host stayed alive while Vite ran as a child'); - } else { + } else if (localMode) { assert.ok( existsSync(cacheProof), 'Vite startup checked the launcher cache before loading its entry point', @@ -65,7 +72,7 @@ try { console.log('vp saved its compile cache before starting Vite'); } - process.kill(pid, 'SIGTERM'); + process.kill(globalMode ? child.pid : pid, 'SIGTERM'); const [code, signal] = await once(child, 'exit', { signal: AbortSignal.timeout(5_000) }); const socket = connect(port, '127.0.0.1'); try { @@ -76,7 +83,7 @@ try { socket.destroy(); } assert.deepEqual([code, signal], [143, null]); - const target = workerMode ? 'Vite child' : 'launch PID'; + const target = workerMode ? 'Vite child' : globalMode ? 'global vp PID' : 'launch PID'; console.log(`SIGTERM to the ${target} closed the port with exit code 143`); } catch (error) { console.error(error); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/snapshots.toml index c4a1c3a5b4..e0ef2d12d0 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/snapshots.toml @@ -11,3 +11,10 @@ vp = "local" skip-platforms = ["windows"] comment = "A Node Worker runs project-local vp dev without replacing its host process." steps = [{ argv = ["node", "probe.mjs", "--worker"], tty = false, timeout = 25000 }] + +[[case]] +name = "command_dev_global_signal" +vp = "global" +skip-platforms = ["windows"] +comment = "SIGTERM sent to the global vp dev PID passes through each wrapper and stops the listening Vite server." +steps = [{ argv = ["node", "probe.mjs", "--global"], tty = false, timeout = 25000 }] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/snapshots/command_dev_global_signal.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/snapshots/command_dev_global_signal.md new file mode 100644 index 0000000000..8f5c196556 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dev_local_signal/snapshots/command_dev_global_signal.md @@ -0,0 +1,10 @@ +# command_dev_global_signal + +SIGTERM sent to the global vp dev PID passes through each wrapper and stops the listening Vite server. + +## `node probe.mjs --global` + +``` +Vite served the project with the client under /probe/ +SIGTERM to the global vp PID closed the port with exit code 143 +``` diff --git a/crates/vp_command/src/lib.rs b/crates/vp_command/src/lib.rs index 59cd6aa935..7ea3ce9cff 100644 --- a/crates/vp_command/src/lib.rs +++ b/crates/vp_command/src/lib.rs @@ -21,6 +21,8 @@ use vt_path::{AbsolutePath, AbsolutePathBuf, RelativePathBuf}; mod external_tool; mod ps1_shim; +#[cfg(unix)] +mod signal_forward; pub use external_tool::{ ExternalToolQuery, FirstPathMatch, classify_first_path_match, find_external_tool, @@ -141,7 +143,8 @@ pub fn exec_node_command(mut cmd: Command) -> Error { /// is interrupted (e.g., via Ctrl+C) while the terminal is in a non-standard state. /// /// On Unix, saves the terminal state before spawning the child process and restores -/// it after the child exits, and ignores SIGINT meanwhile. On Windows, Ctrl+C is ignored +/// it after the child exits, and ignores SIGINT meanwhile. It also forwards SIGTERM and +/// SIGHUP to the child (`SignalForwardGuard`). On Windows, Ctrl+C is ignored /// meanwhile (`ConsoleCtrlGuard`), so this process waits for the child's own cleanup. pub async fn execute_with_terminal_guard(mut cmd: Command) -> Result { // Save terminal state and ignore SIGINT (Unix) or Ctrl+C (Windows) until the child exits. @@ -151,6 +154,8 @@ pub async fn execute_with_terminal_guard(mut cmd: Command) -> Result` signals only this process. Without this +/// guard, this process exits and the child keeps running. SIGINT is not +/// forwarded, because the terminal sends Ctrl+C to the whole process group. +pub(crate) struct SignalForwardGuard { + previous: Vec<(Signal, SigAction)>, +} + +impl SignalForwardGuard { + /// Returns `None` when another guard already forwards to a child. + pub(crate) fn install(pid: u32) -> Option { + let pid = i32::try_from(pid).ok()?; + FORWARD_PID.compare_exchange(0, pid, Ordering::SeqCst, Ordering::SeqCst).ok()?; + let action = + SigAction::new(SigHandler::Handler(forward), SaFlags::SA_RESTART, SigSet::empty()); + let previous = [Signal::SIGTERM, Signal::SIGHUP] + .into_iter() + // Keep a signal that the caller ignores, such as SIGHUP under `nohup`. + .filter(|&signal| !is_ignored(signal)) + .filter_map(|signal| { + // SAFETY: `forward` only calls async-signal-safe functions. + let previous = unsafe { sigaction(signal, &action) }.ok()?; + Some((signal, previous)) + }) + .collect(); + Some(Self { previous }) + } +} + +impl Drop for SignalForwardGuard { + fn drop(&mut self) { + // The child has exited. Stop forwarding before its PID can be reused. + FORWARD_PID.store(0, Ordering::SeqCst); + for (signal, previous) in self.previous.drain(..) { + // SAFETY: reinstalls the disposition captured by `install`. + let _ = unsafe { sigaction(signal, &previous) }; + } + } +} + +/// Reads the disposition without replacing it. +fn is_ignored(signal: Signal) -> bool { + let mut current = MaybeUninit::::uninit(); + // SAFETY: a null action only writes the current disposition to `current`. + unsafe { + libc::sigaction(signal as libc::c_int, std::ptr::null(), current.as_mut_ptr()) == 0 + && current.assume_init().sa_sigaction == libc::SIG_IGN + } +} + +extern "C" fn forward(signal: libc::c_int) { + let pid = FORWARD_PID.load(Ordering::SeqCst); + if pid > 0 { + // SAFETY: `kill` is async-signal-safe. + unsafe { libc::kill(pid, signal) }; + } +}