expression

Register a Ctrl-C cancellation request

Ctrl-C handling differs between operating systems. The ctrlc crate invokes a registered closure on its own handler thread. Record a cancellation request rather than doing lengthy work or terminating from the handler. Register once at program startup and propagate registration errors. This fixture registers a handler then exits without sending a signal; the output confirms only successful registration, not delivery. The cancellation flag alone does not publish other shared data. Fixture: Expected stdout (not executed): handler registered Expected stderr: (empty) Expected exit: 0 Common mistake: Registering a handler for every request or assuming Ctrl-C rolls back completed writes.

Formal Syntax & Structure

rust syntaxrust
ctrlc::set_handler(move || flag.store(true, Ordering::Relaxed))

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    use std::sync::{Arc, atomic::{AtomicBool, Ordering}};    let cancelled = Arc::new(AtomicBool::new(false));    let flag = Arc::clone(&cancelled);    ctrlc::set_handler(move || flag.store(true, Ordering::Relaxed))?;    println!("handler registered");    Ok(())}
Rust Reference