Expand description
Simple handling of Ctrl+C for CLI programs.
ctrlc provides a simple, cross-platform way to set a handler
for the Ctrl+C signal (SIGINT on Unix, CTRL_C_EVENT on Windows).
It spawns a dedicated signal-handling thread
and invokes a user-provided closure when the signal is received.
The typical pattern is to pair a handler with an AtomicBool
that the main loop checks to know when to shut down gracefully.
§Examples
Graceful shutdown with an atomic flag:
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let running = Arc::new(AtomicBool::new(true));
let r = running.clone();
ctrlc::set_handler(move || {
r.store(false, Ordering::SeqCst);
}).expect("Error setting Ctrl-C handler");
while running.load(Ordering::SeqCst) {
// Do work...
break; // (break immediately for doctest)
}
println!("Shutting down.");Enums§
- Error
- Ctrl-C error.
- Signal
Type - A cross-platform way to represent Ctrl-C or program termination signal. Other
signals/events are supported via
Other-variant.
Functions§
- set_
handler - Register signal handler for Ctrl-C.
- try_
set_ handler - The same as ctrlc::set_handler but errors if a handler already exists for the signal(s).
Type Aliases§
- Signal
- Platform specific signal type