use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopMode {
Flag,
Exit,
}
static STOP: AtomicBool = AtomicBool::new(false);
pub fn stop_requested() -> bool {
STOP.load(Ordering::Relaxed)
}
pub fn on_stop_signal(mode: StopMode) {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let handler: extern "C" fn(libc::c_int) = match mode {
StopMode::Flag => record_stop,
StopMode::Exit => exit_now,
};
for signal in [libc::SIGTERM, libc::SIGINT] {
unsafe {
let mut action: libc::sigaction = std::mem::zeroed();
action.sa_sigaction = handler as usize;
libc::sigemptyset(&mut action.sa_mask);
action.sa_flags = libc::SA_RESTART;
libc::sigaction(signal, &action, std::ptr::null_mut());
}
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
let _ = mode;
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
extern "C" fn record_stop(_signal: libc::c_int) {
STOP.store(true, Ordering::Relaxed);
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
extern "C" fn exit_now(_signal: libc::c_int) {
unsafe { libc::_exit(0) }
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod tests {
use super::*;
#[test]
fn a_stop_signal_sets_the_flag_instead_of_ending_the_process() {
on_stop_signal(StopMode::Flag);
assert!(!stop_requested());
unsafe {
libc::raise(libc::SIGTERM);
}
assert!(stop_requested());
}
}