catch sygnal in rust

In Rust, you can use the ctrlc crate to catch signals like SIGINT (Ctrl+C). Here's an example demonstrating how to catch the SIGINT signal in Rust using the ctrlc crate:

First, add the following dependencies to your Cargo.toml file:

[dependencies]
ctrlc = "3.3.0"
31 chars
3 lines

Then you can use the following code to catch the SIGINT signal:

main.rs
extern crate ctrlc;

fn main() {
    // Set up a handler to catch the Ctrl+C signal
    let handler = ctrlc::set_handler(move || {
        println!("Received Ctrl+C signal!");
    });

    // Wait until the handler is done
    if let Err(err) = handler {
        eprintln!("Error setting Ctrl+C handler: {}", err);
    } else {
        // Perform your application logic here
        println!("Press Ctrl+C to trigger the handler...");
    }

    // Keep the main thread alive
    loop {}
}
490 chars
20 lines

When you run the program, it will print "Press Ctrl+C to trigger the handler..." and wait for you to press Ctrl+C. When you do, it will print "Received Ctrl+C signal!".

Remember to replace the println! statements with your actual signal handling logic.

related categories

gistlibby LogSnag