Created
December 6, 2019 03:48
-
-
Save takaswie/ded48047759dd25fe4c9308583fa074d to your computer and use it in GitHub Desktop.
A Rust sample to install signal handler to quit event loop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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