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.