2 releases
Uses old Rust 2015
0.1.1 | Nov 5, 2016 |
---|---|
0.1.0 | Mar 15, 2016 |
#14 in #shutdown-signal
7KB
50 lines
Graceful
Shutdown gracefully.
Usage
See simple.rs for a simple example.
License
Graceful is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0), with portions covered by various BSD-like licenses.
See LICENSE-APACHE and LICENSE-MIT for details.
lib.rs
:
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();
});
}
Dependencies
~2MB
~39K SLoC