Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch signals in Rust

Tags:

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 function calls in general.

But in the current Rust version (0.12 nightly) it seems like that std::io::signal::Listener was removed. Did it get put somewhere else? If so can someone point me to how to catch a signal?

like image 926
bantl23 Avatar asked Oct 09 '14 14:10

bantl23


2 Answers

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<Error>> {     let signals = Signals::new(&[SIGTERM])?;      thread::spawn(move || {         for sig in signals.forever() {             println!("Received signal {:?}", sig);         }     });      Ok(()) } 
like image 133
Blue Avatar answered Nov 09 '22 23:11

Blue


I believe that std::io::signal module was removed in this pull request. It is claimed that proper signals handling was never implemented properly for native runtime, so you likely wouldn't be able to use it now anyway. This seems to be a tracking issue for this problem.

In the meantime, I think, you will have to drop down to the lowest-level unsafe functions from libc.

like image 40
Vladimir Matveev Avatar answered Nov 10 '22 00:11

Vladimir Matveev