use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
static SHUTDOWN_PTR: AtomicUsize = AtomicUsize::new(0);
extern "C" fn signal_handler(_sig: libc::c_int) {
let ptr = SHUTDOWN_PTR.load(Ordering::Relaxed);
if ptr != 0 {
let flag = unsafe { &*(ptr as *const AtomicBool) };
if flag.swap(true, Ordering::Relaxed) {
unsafe { libc::_exit(1) };
}
}
}
pub fn install_shutdown_handler(shutdown: &Arc<AtomicBool>) {
SHUTDOWN_PTR.store(Arc::as_ptr(shutdown) as usize, Ordering::Relaxed);
unsafe {
libc::signal(
libc::SIGINT,
signal_handler as *const () as libc::sighandler_t,
);
libc::signal(
libc::SIGTERM,
signal_handler as *const () as libc::sighandler_t,
);
}
}
pub fn try_lock_memory() {
let unlim = libc::rlimit {
rlim_cur: libc::RLIM_INFINITY,
rlim_max: libc::RLIM_INFINITY,
};
let setrlimit_rc = unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &unlim) };
if setrlimit_rc != 0 {
let err = std::io::Error::last_os_error();
tracing::warn!(
error = %err,
"could not raise RLIMIT_MEMLOCK; mlockall may fail or be capped"
);
}
let flags = libc::MCL_CURRENT | libc::MCL_FUTURE | libc::MCL_ONFAULT;
let rc = unsafe { libc::mlockall(flags) };
if rc == 0 {
tracing::info!("mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) succeeded");
} else {
let err = std::io::Error::last_os_error();
tracing::warn!(
error = %err,
"mlockall failed; running without memory lock — tail latency may be affected"
);
}
}