Expand description
Gracefully shutdown.
(Unix) Async signals are tricky to handle properly. This utility let you block the main thread and execute arbitrary (thread-safe) code to shutdown the process gracefully.
§Usage
- Initialize a SignalGuard before creating any additional threads.
- The SignalGuard will block necessary signals
(
SIGINT
,SIGQUIT
andSIGTERM
on *nix,Ctrl+C
andCtrl+Break
on Windows) during initialization. - Spawn new threads to do the real work.
- Register a handle to properly shutdown the application.
- The main thread will be blocked until a signal is received.
- The handler will run in the main thread.
- On Windows the process will terminate after the handler returns (and
potentially any libc
atexit
handlers).
§Example
extern crate graceful;
use std::sync::atomic::{ATOMIC_BOOL_INIT, AtomicBool, Ordering};
use std::time::Duration;
use std::thread;
use graceful::SignalGuard;
static STOP: AtomicBool = ATOMIC_BOOL_INIT;
fn main() {
let signal_guard = SignalGuard::new();
let handle = thread::spawn(|| {
println!("Worker thread started. Type Ctrl+C to stop.");
while !STOP.load(Ordering::Acquire) {
println!("working...");
thread::sleep(Duration::from_millis(500));
}
println!("Bye.");
});
signal_guard.at_exit(move |sig| {
println!("Signal {} received.", sig);
STOP.store(true, Ordering::Release);
handle.join().unwrap();
});
}