Detegr / rust-ctrlc

Easy Ctrl-C handler for Rust projects
https://crates.io/crates/ctrlc
Other
596 stars 78 forks source link

Multiple set_handler calls don't properly overwrite? 🤔 #118

Open slafs opened 5 months ago

slafs commented 5 months ago

Hello!

Not sure if I'm holding it wrong or... 🤔

The docs for set_handler say:

Will return an error if a system error occurred while setting the handler.

and for try_set_handler say:

Will return an error if another handler exists or if a system error occurred while setting the handler.

But a modified snippet from the README like this:

use ctrlc;
use std::sync::mpsc::channel;

fn main() {
    let (tx, rx) = channel();

    ctrlc::set_handler(move || {}).expect("Error setting Ctrl-C handler");

    ctrlc::set_handler(move || tx.send(()).expect("Could not send signal on channel."))
        .expect("Error setting Ctrl-C handler for the second time");

    println!("Waiting for Ctrl-C...");
    rx.recv().expect("Could not receive from channel.");
    println!("Got it! Exiting...");
}

panics with:

thread 'main' panicked at src/main.rs:10:10:
Error setting Ctrl-C handler for the second time: MultipleHandlers

So it seems set_handler can return MultipleHandlers? 🤔

I'm on OSX 14.4.1

Detegr commented 5 months ago

Hi.

You are correct, this is a bug. It has been there since the introduction of try_set_handler. Quite an obvious bug as well, what have I been thinking :)

Detegr commented 5 months ago

Actually, I'm taking it back. set_handler will overwrite whatever handler there was set by something else than this crate, but it will do it just once. try_set_handler will return MultipleHandlers if something else than this crate had set a handler for the signal.

The wording for the logic is quite poor as my initial thoughts were too that it's not working properly.