Something In The Crate signal_hook Is Puzzling Me

I am learning to develop a command line application via this tutorial shown in Rust's official website.( Signal handling - Command Line Applications in Rust (rust-cli.github.io)) But an code example in the tutorial is puzzling me:

use signal_hook::{consts::SIGINT, iterator::Signals};
use std::{error::Error, thread, time::Duration};

fn main() -> Result<(), Box<dyn Error>> {
    let mut signals = Signals::new(&[SIGINT])?;

    thread::spawn(move || {
        for sig in signals.forever() {
            println!("Received signal {:?}", sig);
        }
    });

    // Following code does the actual work, and can be interrupted by pressing
    // Ctrl-C. As an example: Let's wait a few seconds.
    thread::sleep(Duration::from_secs(2));

    Ok(())
}

The point is the first line. The complier told me that signal_hook::iterator didn't exist:

$ cargo check
    Checking experiment v0.1.0 (C:\Users\xiaog\projects\experiment)
error[E0432]: unresolved import `signal_hook::iterator`
 --> src\main.rs:1:35
  |
1 | use signal_hook::{consts::SIGINT, iterator::Signals};
  |                                   ^^^^^^^^ could not find `iterator` in `signal_hook`

For more information about this error, try `rustc --explain E0432`.
error: could not compile `experiment` (bin "experiment") due to previous error

How can I solve it?
The following is my Cargo.toml. Is it caused by my configuration?

[package]
name = "experiment"
version = "0.1.0"
edition = "2021"

[dependencies]
signal-hook = "0.3.17"

There's a hint in the documentation that this module is for "Non-Windows and iterator" -- the latter being a crate feature that is already enabled by default. So I'm guessing you're on Windows?

1 Like

Thank you!!! I am indeed on Windows! But is there an alternative to iterator on Windows?

I guess you can still just flag polling, but that's admittedly not as nice.

Unix signals are unix specific, so you only need to worry about them if you're doing specific unixy things for unixy platforms. If you aren't, you can safely ignore general signal handling and use the ctrlc crate mentioned first instead of doing direct signal handler manipulation.

Note the portability section of the signal-hook documentation, which starts with

It should work on any POSIX.1-2001 system, which are all the major big OSes with the notable exception of Windows. [emphasis mine]

1 Like