diff --git a/crates/rns-runtime/src/lifecycle.rs b/crates/rns-runtime/src/lifecycle.rs index 2281d6b..405cead 100644 --- a/crates/rns-runtime/src/lifecycle.rs +++ b/crates/rns-runtime/src/lifecycle.rs @@ -75,23 +75,50 @@ impl Default for ExitHandler { } } -/// Install Ctrl-C / SIGTERM handlers that trip `shutdown`. Returned receiver +/// Install a Ctrl-C (SIGINT) handler that trips `shutdown`. Returned receiver /// yields once on signal for await-based callers. +/// +/// On unix the OS-level registration happens synchronously in this call — a +/// handler registered inside a spawned task only takes effect once that task +/// is first polled, leaving a window where SIGINT kills the process via the +/// default disposition. pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> { let (tx, rx) = mpsc::channel(1); - let shutdown_clone = shutdown.clone(); - tokio::spawn(async move { - let ctrl_c = tokio::signal::ctrl_c(); - ctrl_c.await.ok(); - tracing::info!("received shutdown signal"); - shutdown_clone.trigger(); - let _ = tx.send(()).await; - }); + + #[cfg(unix)] + match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()) { + Ok(mut sigint) => { + tokio::spawn(async move { + sigint.recv().await; + signal_shutdown(shutdown_clone, tx).await; + }); + } + Err(e) => { + tracing::warn!(error = %e, "SIGINT registration failed; falling back to ctrl_c"); + spawn_ctrl_c_handler(shutdown_clone, tx); + } + } + + #[cfg(not(unix))] + spawn_ctrl_c_handler(shutdown_clone, tx); rx } +fn spawn_ctrl_c_handler(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) { + tokio::spawn(async move { + tokio::signal::ctrl_c().await.ok(); + signal_shutdown(shutdown, tx).await; + }); +} + +async fn signal_shutdown(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) { + tracing::info!("received shutdown signal"); + shutdown.trigger(); + let _ = tx.send(()).await; +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/rns-tools/tests/listener_signal_cli.rs b/crates/rns-tools/tests/listener_signal_cli.rs index 8160592..f1a5e14 100644 --- a/crates/rns-tools/tests/listener_signal_cli.rs +++ b/crates/rns-tools/tests/listener_signal_cli.rs @@ -51,8 +51,8 @@ fn write_config(tmp: &TempDir) { } #[cfg(unix)] -fn wait_until_running(child: &mut Child) -> bool { - let deadline = Instant::now() + Duration::from_secs(3); +fn wait_until_running(child: &mut Child, settle: Duration) -> bool { + let deadline = Instant::now() + settle; while Instant::now() < deadline { if child.try_wait().expect("poll child").is_some() { return false; @@ -62,49 +62,75 @@ fn wait_until_running(child: &mut Child) -> bool { true } +/// Sends SIGINT after a settle period and asserts a clean exit. Retries once +/// with a longer settle if the child died from the raw signal (exit by signal +/// 2): under full-workspace load the child can still be booting when the +/// first SIGINT lands, before its handler is registered. A real handler +/// regression fails both attempts. #[cfg(unix)] -fn assert_sigint_exits(mut child: Child, name: &str) { - if !wait_until_running(&mut child) { - let output = child.wait_with_output().expect("collect child output"); - panic!( - "{name} exited before SIGINT\nstatus: {}\nstdout:\n{}\nstderr:\n{}", - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - } +fn assert_sigint_exits(spawn: impl Fn() -> Child, name: &str) { + use std::os::unix::process::ExitStatusExt; - let status = Command::new("kill") - .arg("-INT") - .arg(child.id().to_string()) - .status() - .expect("send SIGINT"); - assert!(status.success(), "kill -INT failed with {status}"); - - let deadline = Instant::now() + Duration::from_secs(5); - while Instant::now() < deadline { - if let Some(status) = child.try_wait().expect("poll child after SIGINT") { + let settles = [Duration::from_secs(3), Duration::from_secs(8)]; + let last_attempt = settles.len() - 1; + for (attempt, settle) in settles.into_iter().enumerate() { + let mut child = spawn(); + if !wait_until_running(&mut child, settle) { let output = child.wait_with_output().expect("collect child output"); - assert!( - status.success(), - "{name} exited unsuccessfully after SIGINT: {status}\nstdout:\n{}\nstderr:\n{}", + panic!( + "{name} exited before SIGINT\nstatus: {}\nstdout:\n{}\nstderr:\n{}", + output.status, String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr) ); - return; } - thread::sleep(Duration::from_millis(50)); - } - let _ = child.kill(); - let output = child - .wait_with_output() - .expect("collect killed child output"); - panic!( - "{name} did not exit after SIGINT\nstdout:\n{}\nstderr:\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); + let status = Command::new("kill") + .arg("-INT") + .arg(child.id().to_string()) + .status() + .expect("send SIGINT"); + assert!(status.success(), "kill -INT failed with {status}"); + + let deadline = Instant::now() + Duration::from_secs(10); + let exit_status = loop { + if let Some(status) = child.try_wait().expect("poll child after SIGINT") { + break Some(status); + } + if Instant::now() >= deadline { + break None; + } + thread::sleep(Duration::from_millis(50)); + }; + + match exit_status { + Some(status) if status.success() => return, + Some(status) if attempt < last_attempt && status.signal() == Some(2) => { + let _ = child.wait_with_output(); + continue; + } + Some(status) => { + let output = child.wait_with_output().expect("collect child output"); + panic!( + "{name} exited unsuccessfully after SIGINT: {status}\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + None => { + let _ = child.kill(); + let output = child + .wait_with_output() + .expect("collect killed child output"); + panic!( + "{name} did not exit after SIGINT\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + } + } + unreachable!("attempt loop either returns or panics"); } #[cfg(unix)] @@ -112,18 +138,21 @@ fn assert_sigint_exits(mut child: Child, name: &str) { fn rncp_listener_exits_on_sigint() { let tmp = TempDir::new("rncp-sigint"); write_config(&tmp); - let child = Command::new(env!("CARGO_BIN_EXE_rncp-rs")) - .arg("--config") - .arg(tmp.path()) - .arg("-l") - .arg("-n") - .arg("-S") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .expect("spawn rncp-rs listener"); - - assert_sigint_exits(child, "rncp-rs"); + assert_sigint_exits( + || { + Command::new(env!("CARGO_BIN_EXE_rncp-rs")) + .arg("--config") + .arg(tmp.path()) + .arg("-l") + .arg("-n") + .arg("-S") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn rncp-rs listener") + }, + "rncp-rs", + ); } #[cfg(unix)] @@ -131,15 +160,18 @@ fn rncp_listener_exits_on_sigint() { fn rnsh_listener_exits_on_sigint() { let tmp = TempDir::new("rnsh-sigint"); write_config(&tmp); - let child = Command::new(env!("CARGO_BIN_EXE_rnsh-rs")) - .arg("--config") - .arg(tmp.path()) - .arg("-l") - .arg("-n") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .expect("spawn rnsh-rs listener"); - - assert_sigint_exits(child, "rnsh-rs"); + assert_sigint_exits( + || { + Command::new(env!("CARGO_BIN_EXE_rnsh-rs")) + .arg("--config") + .arg(tmp.path()) + .arg("-l") + .arg("-n") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn rnsh-rs listener") + }, + "rnsh-rs", + ); }