Skip to main content

rusty_time_clock/
stop.rs

1//! Stopping on SIGTERM and SIGINT, including as the init process of a PID
2//! namespace.
3//!
4//! Without a handler a process relies on the signal's default action, and the
5//! kernel does not apply a default action to the init process of a PID
6//! namespace: a signal sent from outside reaches it only if it has installed a
7//! handler. OpenWrt's procd runs jailed services exactly that way (ujail puts
8//! the service in its own PID namespace), and so does a container with no init
9//! of its own. There `rtimed` ignored SIGTERM, and procd killed it with SIGKILL
10//! after five seconds on every stop and restart. Installing a handler restores
11//! the stop everywhere, and changes nothing where the default action already
12//! worked.
13//!
14//! Lives in this crate because installing a handler is a syscall, and this is
15//! the one crate permitted `unsafe`.
16
17use std::sync::atomic::{AtomicBool, Ordering};
18
19/// What a stop signal does once a handler is installed.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum StopMode {
22    /// Only record the request, for a loop that polls [`stop_requested`] and
23    /// returns normally.
24    Flag,
25    /// End the process at once, with status 0, as the default action would
26    /// have (for modes whose threads block in receive and have no such loop).
27    Exit,
28}
29
30static STOP: AtomicBool = AtomicBool::new(false);
31
32/// Whether SIGTERM or SIGINT has arrived since [`on_stop_signal`].
33pub fn stop_requested() -> bool {
34    STOP.load(Ordering::Relaxed)
35}
36
37/// Install the SIGTERM and SIGINT handler. A no-op where there are no POSIX
38/// signals.
39pub fn on_stop_signal(mode: StopMode) {
40    #[cfg(any(target_os = "linux", target_os = "macos"))]
41    {
42        let handler: extern "C" fn(libc::c_int) = match mode {
43            StopMode::Flag => record_stop,
44            StopMode::Exit => exit_now,
45        };
46        for signal in [libc::SIGTERM, libc::SIGINT] {
47            // SAFETY: an all-zero `sigaction` is a valid value of the type (no
48            // flags, empty mask before `sigemptyset`, null restorer). The
49            // handler does only async-signal-safe work: an atomic store, or
50            // `_exit`. Replacing the disposition of these two signals affects
51            // nothing else this process relies on.
52            unsafe {
53                let mut action: libc::sigaction = std::mem::zeroed();
54                action.sa_sigaction = handler as usize;
55                libc::sigemptyset(&mut action.sa_mask);
56                action.sa_flags = libc::SA_RESTART;
57                libc::sigaction(signal, &action, std::ptr::null_mut());
58            }
59        }
60    }
61    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
62    {
63        let _ = mode;
64    }
65}
66
67#[cfg(any(target_os = "linux", target_os = "macos"))]
68extern "C" fn record_stop(_signal: libc::c_int) {
69    STOP.store(true, Ordering::Relaxed);
70}
71
72#[cfg(any(target_os = "linux", target_os = "macos"))]
73extern "C" fn exit_now(_signal: libc::c_int) {
74    // SAFETY: `_exit` is async-signal-safe and does not return.
75    unsafe { libc::_exit(0) }
76}
77
78#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn a_stop_signal_sets_the_flag_instead_of_ending_the_process() {
84        on_stop_signal(StopMode::Flag);
85        assert!(!stop_requested());
86        // SAFETY: `raise` delivers SIGTERM to this thread; the handler just
87        // installed records it, so the test process survives.
88        unsafe {
89            libc::raise(libc::SIGTERM);
90        }
91        assert!(stop_requested());
92    }
93}