Crate better_graceful

Source
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

  1. Initialize a SignalGuard before creating any additional threads.
  2. The SignalGuard will block necessary signals (SIGINT, SIGQUIT and SIGTERM on *nix, Ctrl+C and Ctrl+Break on Windows) during initialization.
  3. Spawn new threads to do the real work.
  4. Register a handle to properly shutdown the application.
  5. The main thread will be blocked until a signal is received.
  6. The handler will run in the main thread.
  7. 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();
    });
}

Structs§