1 unstable release

0.1.1 Nov 7, 2021

#11 in #shutdown-signal

MIT/Apache

9KB
61 lines

Graceful

Shutdown gracefully.

API Documentation

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

  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();
    });
}

Dependencies

~2MB
~37K SLoC