//! The signals that end the app against the handler that turns them into its quit cleanup. A //! file of its own, so the handler lives in a test process of its own: without it, a signal below //! ends the whole process and the run fails. The handler installs once per process, so every //! other case runs in a child: this test binary again, running only `signal_child`. #![cfg(unix)] use std::io::{BufRead, BufReader, IsTerminal, Write}; use std::os::fd::{FromRawFd, OwnedFd}; use std::os::unix::process::ExitStatusExt; use std::process::{Child, Command, ExitStatus, Stdio}; use std::sync::mpsc::channel; use std::time::{Duration, Instant}; use plan2code_app_lib::{log, term_signal}; /// Names the case, and is set only in the child process a test starts. const CHILD: &str = "P2C_TERM_SIGNAL_CHILD"; /// The child's exit codes: its cleanup ran to the end, or it did not when it should have. const CLEANED: i32 = 0; const NOT_CLEANED: i32 = 3; #[test] fn a_sigterm_runs_the_cleanup_instead_of_ending_the_process() { let (tx, rx) = channel(); term_signal::on_terminate(move || { let _ = tx.send(()); }) .expect("the handler installs"); raise(libc::SIGTERM); rx.recv_timeout(Duration::from_secs(5)) .expect("the cleanup ran after SIGTERM"); // A second install is refused: one signal, one cleanup. assert!(term_signal::on_terminate(|| {}).is_err()); } #[test] fn ctrl_c_and_a_closed_terminal_run_the_cleanup_too() { for case in ["sigint", "sighup"] { let status = outcome(child(case).spawn().expect("the child starts")); assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}"); } } #[test] fn a_second_signal_ends_the_app_while_its_cleanup_still_runs() { // A cleanup that stalls must not leave a plain `kill` or Ctrl+C unable to // end the app, whichever signal started it. for (case, ends_by) in [ ("sigterm twice", libc::SIGTERM), ("sigint twice", libc::SIGINT), ("sighup then sigterm", libc::SIGTERM), ] { let status = outcome(child(case).spawn().expect("the child starts")); assert_eq!(status.signal(), Some(ends_by), "{case}: {status:?}"); } } #[test] fn a_repeated_sighup_lets_the_cleanup_finish() { // Closing a terminal can send it twice at once: zsh passes it on to the // program in front, and the terminal's own hangup sends it again. let status = outcome(child("sighup twice").spawn().expect("the child starts")); assert_eq!(status.code(), Some(CLEANED), "{status:?}"); } #[test] fn a_signal_the_app_was_started_with_ignored_stays_ignored() { // `nohup` starts a program with SIGHUP ignored, to outlive its terminal. let status = outcome(child("ignored sighup").spawn().expect("the child starts")); assert_eq!(status.code(), Some(CLEANED), "{status:?}"); } #[test] fn a_command_the_cleanup_runs_outlives_a_repeated_sighup() { // The cleanup stops consoles by running `node`, which the second SIGHUP of // a closed terminal would end before it stopped anything. let status = outcome(child("command").spawn().expect("the child starts")); assert_eq!(status.code(), Some(CLEANED), "{status:?}"); } #[test] fn a_cleanup_that_logs_after_its_terminal_is_gone_still_finishes() { for case in ["sighup, closed terminal", "sigterm, closed terminal"] { logs_to_a_closed_terminal(case); } } /// Runs the child on a terminal of its own, and closes that terminal once the /// child has its handler. fn logs_to_a_closed_terminal(case: &str) { let (mut master, mut slave) = (-1, -1); // SAFETY: openpty fills the two descriptors; the name and settings are optional. let opened = unsafe { libc::openpty( &mut master, &mut slave, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), ) }; assert_eq!(opened, 0, "openpty: {}", std::io::Error::last_os_error()); // SAFETY: both descriptors were just opened, and nothing else owns them. Close-on-exec keeps // the terminal's other end out of the child, which would hold it open. let (master, slave) = unsafe { libc::fcntl(master, libc::F_SETFD, libc::FD_CLOEXEC); (OwnedFd::from_raw_fd(master), OwnedFd::from_raw_fd(slave)) }; let mut child = child(case) .stdout(Stdio::piped()) .stderr(Stdio::from(slave)) .spawn() .expect("the child starts"); let stdout = child.stdout.take().expect("the child's stdout is piped"); let ready = BufReader::new(stdout) .lines() .map_while(Result::ok) .any(|line| line.ends_with("ready")); assert!(ready, "the child installed the handler"); drop(master); let status = outcome(child); assert_eq!(status.code(), Some(CLEANED), "{case}: {status:?}"); } fn raise(signal: libc::c_int) { // SAFETY: raise only sends this process a signal. assert_eq!(unsafe { libc::raise(signal) }, 0); } /// This test binary again, running only `signal_child` on `case`. fn child(case: &str) -> Command { let mut command = Command::new(std::env::current_exe().expect("the test binary")); command .args(["--exact", "signal_child", "--test-threads=1", "--nocapture"]) .env(CHILD, case) .stdout(Stdio::null()) .stderr(Stdio::null()); command } /// How the child ended, within 30 s. fn outcome(mut child: Child) -> ExitStatus { let deadline = Instant::now() + Duration::from_secs(30); loop { if let Some(status) = child.try_wait().expect("the child can be waited on") { return status; } if Instant::now() > deadline { let _ = child.kill(); let _ = child.wait(); panic!("the child neither ended nor exited within 30 s"); } std::thread::sleep(Duration::from_millis(50)); } } /// Not a check on its own: the child process of the tests above. Run any other /// way, it returns at once. #[test] fn signal_child() { let Some(case) = std::env::var_os(CHILD) else { return; }; // A signal this run was started with ignored (`nohup`, a script's `&`) // would stay ignored, and no case below means that one. for signal in [libc::SIGTERM, libc::SIGINT, libc::SIGHUP] { // SAFETY: putting a signal's default action back installs no handler. unsafe { libc::signal(signal, libc::SIG_DFL) }; } match case.to_str().expect("a case name") { "sigint" => cleans_up_after(&[libc::SIGINT]), "sighup" => cleans_up_after(&[libc::SIGHUP]), "sighup twice" => cleans_up_after(&[libc::SIGHUP, libc::SIGHUP]), "sigterm twice" => ends_during_the_cleanup(libc::SIGTERM, libc::SIGTERM), "sigint twice" => ends_during_the_cleanup(libc::SIGINT, libc::SIGINT), "sighup then sigterm" => ends_during_the_cleanup(libc::SIGHUP, libc::SIGTERM), "ignored sighup" => ignores_sighup(), "command" => runs_a_command_through_a_sighup(), "sighup, closed terminal" => logs_after_its_terminal_closed(libc::SIGHUP), "sigterm, closed terminal" => logs_after_its_terminal_closed(libc::SIGTERM), other => panic!("no such case: {other}"), } } /// The cleanup takes a moment, so a signal that ends the app would cut it short. fn cleans_up_after(signals: &[libc::c_int]) { term_signal::on_terminate(|| { std::thread::sleep(Duration::from_millis(300)); std::process::exit(CLEANED); }) .expect("the handler installs"); for signal in signals { raise(*signal); } std::thread::sleep(Duration::from_secs(5)); std::process::exit(NOT_CLEANED); } fn ends_during_the_cleanup(first: libc::c_int, second: libc::c_int) { let (tx, rx) = channel(); term_signal::on_terminate(move || { let _ = tx.send(()); // A cleanup that never finishes. loop { std::thread::sleep(Duration::from_secs(60)); } }) .expect("the handler installs"); raise(first); rx.recv_timeout(Duration::from_secs(5)) .expect("the first signal started the cleanup"); raise(second); // Still running: the second signal was swallowed. std::thread::sleep(Duration::from_secs(2)); std::process::exit(NOT_CLEANED); } fn ignores_sighup() { // SAFETY: ignoring a signal installs no handler. unsafe { libc::signal(libc::SIGHUP, libc::SIG_IGN) }; term_signal::on_terminate(|| std::process::exit(NOT_CLEANED)).expect("the handler installs"); raise(libc::SIGHUP); std::thread::sleep(Duration::from_secs(1)); std::process::exit(CLEANED); } fn runs_a_command_through_a_sighup() { term_signal::on_terminate(|| { let status = Command::new("/bin/sh") .args(["-c", "kill -HUP $$; exit 0"]) .status() .expect("sh runs"); std::process::exit(if status.success() { CLEANED } else { NOT_CLEANED }); }) .expect("the handler installs"); raise(libc::SIGHUP); std::thread::sleep(Duration::from_secs(5)); std::process::exit(NOT_CLEANED); } fn logs_after_its_terminal_closed(signal: libc::c_int) { assert!(std::io::stderr().is_terminal(), "stderr is a terminal"); term_signal::on_terminate(|| { log::line("a line from the cleanup"); std::process::exit(CLEANED); }) .expect("the handler installs"); println!("ready"); // Closed once a write fails: macOS reports neither a hangup nor a lost terminal here. let deadline = Instant::now() + Duration::from_secs(10); while std::io::stderr().write_all(b".").is_ok() { assert!(Instant::now() < deadline, "the terminal never closed"); std::thread::sleep(Duration::from_millis(10)); } raise(signal); std::thread::sleep(Duration::from_secs(5)); std::process::exit(NOT_CLEANED); }