1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#[macro_use] extern crate lazy_static;
extern crate signal_simple;

use signal_simple::signal::{signal as sig, SIGTERM, SIGINT, int};
use signal_simple::channel::SyncChannel;

lazy_static! {
    static ref TERM_HANDLER_CHANNEL: SyncChannel<()> = SyncChannel::new();
}

fn term_handler(_: int) {
    TERM_HANDLER_CHANNEL.send(()).unwrap();
}

pub fn wait_for_term() {
    sig(SIGTERM, term_handler, None);
    sig(SIGINT, term_handler, None);

    loop {
        if let Ok(Some(_)) = TERM_HANDLER_CHANNEL.try_recv() {
            break;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use signal_simple::signal::kill;

    #[test]
    fn test_term() {
        ::std::thread::spawn(|| {
            ::std::thread::sleep(::std::time::Duration::from_secs(2));
            kill(SIGTERM);
        });
        wait_for_term();
    }
}