use std::ffi::c_int;
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
pub const SIGHUP: i32 = 1;
pub const SIGINT: i32 = 2;
pub const SIGTERM: i32 = 15;
static PENDING: AtomicI32 = AtomicI32::new(0);
static INSTALLED: AtomicBool = AtomicBool::new(false);
static STOPPING: AtomicBool = AtomicBool::new(false);
const SIG_DFL: usize = 0;
const SIG_IGN: usize = 1;
const SIGKILL: c_int = 9;
const EPERM: i32 = 1;
unsafe extern "C" {
fn signal(signum: c_int, handler: usize) -> usize;
fn raise(signum: c_int) -> c_int;
fn kill(pid: c_int, sig: c_int) -> c_int;
fn _exit(status: c_int) -> !;
}
extern "C" fn on_signal(sig: c_int) {
if PENDING.swap(sig, Ordering::SeqCst) != 0 {
unsafe { _exit(128 + sig) }
}
}
pub fn install() {
if INSTALLED.swap(true, Ordering::SeqCst) {
return;
}
let handler = on_signal as extern "C" fn(c_int) as usize;
for sig in [SIGHUP, SIGINT, SIGTERM] {
unsafe {
if signal(sig, handler) == SIG_IGN {
signal(sig, SIG_IGN);
}
}
}
}
pub fn kill_group(pgid: u32) {
if pgid > 1 && pgid <= i32::MAX as u32 {
unsafe {
kill(-(pgid as c_int), SIGKILL);
}
}
}
pub fn alive(pid: u32, group: bool) -> bool {
if pid <= 1 || pid > i32::MAX as u32 {
return false;
}
let target = if group { -(pid as c_int) } else { pid as c_int };
let sent = unsafe { kill(target, 0) };
sent == 0 || std::io::Error::last_os_error().raw_os_error() == Some(EPERM)
}
pub fn installed() -> bool {
INSTALLED.load(Ordering::SeqCst)
}
pub fn pending() -> Option<i32> {
match PENDING.load(Ordering::SeqCst) {
0 => None,
sig => Some(sig),
}
}
pub fn request_stop() {
STOPPING.store(true, Ordering::SeqCst);
}
pub fn interrupted() -> bool {
pending().is_some() || STOPPING.load(Ordering::SeqCst)
}
pub fn name(sig: i32) -> &'static str {
match sig {
SIGHUP => "SIGHUP",
SIGINT => "SIGINT",
SIGTERM => "SIGTERM",
_ => "signal",
}
}
pub fn die_by(sig: i32) -> ! {
use std::io::Write;
let _ = std::io::stdout().flush();
let _ = std::io::stderr().flush();
unsafe {
signal(sig, SIG_DFL);
raise(sig);
}
std::process::exit(128 + sig)
}