Skip to content

Instantly share code, notes, and snippets.

@takaswie
Created December 6, 2019 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takaswie/ded48047759dd25fe4c9308583fa074d to your computer and use it in GitHub Desktop.
Save takaswie/ded48047759dd25fe4c9308583fa074d to your computer and use it in GitHub Desktop.
A Rust sample to install signal handler to quit event loop.
extern crate nix;
extern crate libc;
use nix::sys::signal;
use std::sync::atomic::{AtomicBool, Ordering};
static RUNNING: AtomicBool = AtomicBool::new(false);
extern "C" fn handle(_: libc::c_int, _: *mut libc::siginfo_t,
_: *mut libc::c_void) {
RUNNING.store(false, Ordering::SeqCst);
}
fn install_signal_handler() -> bool {
let result = unsafe {
let sig_action = signal::SigAction::new(
signal::SigHandler::SigAction(handle),
signal::SaFlags::empty(),
signal::SigSet::empty());
signal::sigaction(signal::SIGINT, &sig_action)
};
if let Err(err) = result {
print!("Fail to install signal handlers due to: ");
match err {
nix::Error::Sys(errno) =>
println!("{} ({}).", errno.desc(), errno),
_ =>
println!("unexpected cause."),
};
return false;
}
return true;
}
fn main() {
if install_signal_handler() == false {
std::process::exit(1)
}
RUNNING.store(true, Ordering::SeqCst);
while RUNNING.load(Ordering::Relaxed) == true {
}
std::process::exit(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment