use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use crate::Stopper;
static REQUESTED: AtomicBool = AtomicBool::new(false);
static DEFERRED: AtomicBool = AtomicBool::new(false);
static FORCED: AtomicBool = AtomicBool::new(false);
fn on_signal_flags() -> bool {
if !REQUESTED.swap(true, Ordering::SeqCst) {
return true;
}
DEFERRED.load(Ordering::SeqCst) && !FORCED.swap(true, Ordering::SeqCst)
}
pub fn install() -> bool {
sys::install()
}
pub fn requested() -> bool {
REQUESTED.load(Ordering::SeqCst)
}
pub fn on_signal(f: impl FnOnce() + Send + 'static) -> bool {
if !install() {
return false;
}
std::thread::Builder::new()
.name("tvpipe-signals".into())
.spawn(move || {
while !requested() {
std::thread::sleep(Duration::from_millis(20));
}
f();
})
.is_ok()
}
pub fn before_forced_exit(f: impl FnOnce() + Send + 'static) -> bool {
let started = std::thread::Builder::new()
.name("tvpipe-forced-exit".into())
.spawn(move || {
while !FORCED.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(20));
}
f();
std::process::exit(130);
})
.is_ok();
if started {
DEFERRED.store(true, Ordering::SeqCst);
}
started
}
pub fn stop_on_signal(stopper: Stopper) -> bool {
on_signal(move || stopper.stop())
}
#[cfg(unix)]
mod sys {
const SIGINT: i32 = 2;
const SIGTERM: i32 = 15;
const SIG_ERR: usize = usize::MAX;
extern "C" {
fn signal(signum: i32, handler: usize) -> usize;
fn _exit(status: i32) -> !;
}
extern "C" fn on_signal(_signum: i32) {
if !super::on_signal_flags() {
unsafe { _exit(130) }
}
}
pub fn install() -> bool {
let handler = on_signal as extern "C" fn(i32) as usize;
unsafe { signal(SIGINT, handler) != SIG_ERR && signal(SIGTERM, handler) != SIG_ERR }
}
}
#[cfg(windows)]
mod sys {
const CTRL_C_EVENT: u32 = 0;
const CTRL_BREAK_EVENT: u32 = 1;
type HandlerRoutine = unsafe extern "system" fn(u32) -> i32;
#[link(name = "kernel32")]
extern "system" {
fn SetConsoleCtrlHandler(handler: Option<HandlerRoutine>, add: i32) -> i32;
}
unsafe extern "system" fn on_ctrl(event: u32) -> i32 {
match event {
CTRL_C_EVENT | CTRL_BREAK_EVENT => super::on_signal_flags() as i32,
_ => 0,
}
}
pub fn install() -> bool {
unsafe { SetConsoleCtrlHandler(Some(on_ctrl), 1) != 0 }
}
}
#[cfg(not(any(unix, windows)))]
mod sys {
pub fn install() -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn installs() {
assert!(install());
assert!(install(), "installing twice is fine");
assert!(!requested());
}
}