2 releases

0.1.1 Jan 10, 2023
0.1.0 Jan 9, 2023

#449 in Operating systems

31 downloads per month

MIT/Apache

12KB
161 lines

ragequit

Crates.io Docs.rs

Gracefully shut down a process

ragequit provides a set of utilities to shut down a process. It is primarily targeted at server processes, but may have other applications aswell.

Usage

The global SHUTDOWN instance is used to signal shutdown events and handle them gracefully by creating ShutdownListeners.

use ragequit::{init, SHUTDOWN};

#[tokio::main]
async fn main() {
    // Install default system signal handlers.
    init();

    let listener = SHUTDOWN.listen();
    tokio::spawn(async move {
        // Wait for the shutdown signal.
        tokio::pin!(listener);
        (&mut listener).await;

        // Drop the listener, allowing the main process to exit.
        println!("Goodbye");
        drop(listener);
    });

    // Wait for a shutdown signal and for all listeners to be dropped.
    SHUTDOWN.wait().await;
}

Call init once during the start of the process to install the default system signal handlers. Alternatively you can install system signal handlers yourself.

Example for *nix systems

use core::ffi::c_int;

use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};
use ragequit::SHUTDOWN;

let action = SigAction::new(SigHandler::Handler(quit), SaFlags::empty(), SigSet::empty());

unsafe {
    let _ = sigaction(Signal::SIGINT, &action);
    let _ = sigaction(Signal::SIGTERM, &action);
}

extern "C" fn quit(_: c_int) {
    SHUTDOWN.quit();
}

Tokio dependency

ragequit depends on tokio only for synchronization primitives. It does not depend on the tokio runtime. ragequit works in any asynchronous runtime.

License

Licensed under either MIT License or Apache License, Version 2.0 at your option.

Dependencies

~3–15MB
~180K SLoC