rust-cookbook icon indicating copy to clipboard operation
rust-cookbook copied to clipboard

Unix signal handling

Open ghost opened this issue 6 years ago • 4 comments
trafficstars

It'd be nice to include an example for signal handling on Unix-like platforms.

Currently, the go-to solution is to look up chan-signal (which is deprecated) and then copy-paste the example for the readme that is using signal-hook and crossbeam-channel:

extern crate crossbeam_channel as channel;
extern crate signal_hook;

fn notify(signals: &[c_int]) -> Result<channel::Receiver<c_int>> {
    let (s, r) = channel::bounded(100);
    let signals = signal_hook::iterator::Signals::new(signals)?;
    thread::spawn(move || {
        for signal in signals.forever() {
            s.send(signal);
        }
    });
    Ok(r)
}

By the way, I have a question: why are we creating a bounded(100) channel rather than unbounded()?

Also, check out this stopwatch that shows a neat example of using signal-hook and crossbeam-channel with the tick channel and select!. Perhaps we could add something like it to the cookbook.

cc @vorner @BurntSushi

ghost avatar Nov 28 '18 16:11 ghost

By the way, I have a question: why are we creating a bounded(100) channel rather than unbounded()

My guess is, bounded channels are considered the „default“ and unbounded are used only if you have some reasons. Mostly because with bounded channels, there's no risk of exhausting the RAM if the reader doesn't keep up.

If the write end becomes blocked, the signals will get coalesced together, which is usually fine.

vorner avatar Nov 28 '18 19:11 vorner

@vorner's reasoning is exactly why I did it. I always try to use bounded channels unless there's a specific good reason to do otherwise.

BurntSushi avatar Nov 28 '18 19:11 BurntSushi

Makes sense. But... (I don't know a lot about signal-hook) does that mean some signals could be dropped, e.g. if we send 1000 signals in quick succession?

ghost avatar Nov 28 '18 21:11 ghost

It means that some instances of the signals might be dropped. But you'll always get at least one of each kind ‒ so if someone sends you 950* SIGINT and 50* SIGUSR1, you'll get at least one of each.

This is not a speciality of signal-hook, it's how the OS works ‒ signals have a flag semantics, if they happened since last time anyone looked, not how many times. Signal-hook only can magnify the effect under some circumstances.

vorner avatar Nov 29 '18 09:11 vorner