How to catch signals in Rust

前端 未结 3 1277
说谎
说谎 2020-12-17 10:22

I\'m trying to write some code that will catch a signal like SIGTERM.

I found this and I also found How to handle blocking i/o in Rust, or long running external func

3条回答
  •  执念已碎
    2020-12-17 10:59

    It seems that it's now fairly trivial to implement this. The Signal handling section of Command Line Applications in Rust goes over the concept, and mentions the ctrlc crate to handle that specific signal, and the signal-hook crate to handle signals in general.

    Via the guide, with signal-hook it should be as simple as:

    use std::{error::Error, thread};
    use signal_hook::{iterator::Signals, SIGTERM};
    
    fn main() -> Result<(), Box> {
        let signals = Signals::new(&[SIGTERM])?;
    
        thread::spawn(move || {
            for sig in signals.forever() {
                println!("Received signal {:?}", sig);
            }
        });
    
        Ok(())
    }
    

提交回复
热议问题