simple_sigh/lib.rs
1#![allow(clippy::needless_doctest_main)]
2//! A simple signal handler.
3//!
4//! On unix, register `SIGINT`/`SIGTERM` signal handlers that call a closure to
5//! process the signals. On Windows, register "console control" handlers to
6//! call a closure on Ctrl+C, Ctrl+Break and close events.
7//!
8//! The closure is called once and it is assumed that it will cause the
9//! application to terminate.
10//!
11//! # Usage
12//! The application must call [`init()`] early (before setting up any other
13//! signal handlers or spawning threads). After `init()` has been called, it
14//! must call [`register()`] to set the callback closure that will be called
15//! when one of the signals of interest is raised.
16//!
17//! ## Waiting for termination requests
18//! Applications that are run on spawned threads can use signaling mechanisms
19//! like a `Condvar` or a channel to signal from the signal handler to `main()`
20//! that the application should be terminated. However, because it is assumed
21//! that this is a somewhat common use-case for `simple-sigh` it provides a
22//! pre-baked solution for this pattern: `init()` returns a [`KillWait`] object
23//! that has a [`KillWait::wait()`] method that will block indefinitely and
24//! wait for the signal handler to trigger.
25//!
26//! ```no_run
27//! fn main() {
28//! let kw = simple_sigh::init().unwrap();
29//!
30//! // .. spawen application thread here ..
31//!
32//! // Set a signal handler callback
33//! simple_sigh::register(move |_| {
34//! println!("Received signal");
35//! // .. signal application runtime to terminate here ..
36//! })
37//! .unwrap();
38//!
39//! // Wait for some kind of abortion signal to be received
40//! println!("Wait for interrupt/termination signal..");
41//! kw.wait();
42//! println!("Bye!");
43//! }
44//! ```
45//!
46//! ## Known limitations
47//! `simple-sigh` isn't intended for production; it was originally designed for
48//! use in examples, and it may be lossy with regards to error handling.
49//! The general rule is that `simple-sigh` belongs in `dev-dependencies` rather
50//! than `dependencies`.
51
52mod err;
53
54#[cfg(unix)]
55mod unix;
56
57#[cfg(windows)]
58mod win;
59
60pub use err::Error;
61
62#[cfg(unix)]
63pub use unix::{init, register, KillWait};
64
65#[cfg(windows)]
66pub use win::{init, register, KillWait};
67
68/// Signal type that caused the signal handler to run.
69pub enum SigType {
70 /// `SIGINT` on unixy systems. Ctrl+C on Windows.
71 Int,
72
73 /// `SIGTERM` on unixy systems. Ctrl+Break or console close on Windows.
74 Term
75}
76
77// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :