How to Handle Signals (Ctrl+C) in Rust (ctrlc crate)

Cli
Handle Ctrl+C in Rust by adding the ctrlc crate, setting a signal handler to flip an atomic flag, and checking that flag in your main loop to exit gracefully.

Add the ctrlc crate to your dependencies and register a handler function that sets a shared flag when Ctrl+C is pressed, then check that flag in your main loop to exit gracefully.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;

fn main() {
    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();

    ctrlc::set_handler(move || {
        println!("Received Ctrl+C, shutting down...");
        r.store(false, Ordering::SeqCst);
    }).expect("Error setting Ctrl-C handler");

    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {i} from the spawned thread!");
            thread::sleep(Duration::from_millis(1));
        }
    });

    while running.load(Ordering::SeqCst) {
        println!("Main thread is running...");
        thread::sleep(Duration::from_millis(100));
    }

    handle.join().unwrap();
    println!("Program exited gracefully.");
}

Add ctrlc = "3.4" to your Cargo.toml dependencies.