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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use std::sync::atomic::Ordering;
use std::thread;
use std::time;
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT};
static DONE: AtomicBool = ATOMIC_BOOL_INIT;
#[cfg(unix)]
mod platform {
extern crate libc;
use self::libc::c_int;
use self::libc::sighandler_t;
use self::libc::SIGINT;
#[cfg(feature = "termination")]
use self::libc::SIGTERM;
use self::libc::signal;
use std::sync::atomic::Ordering;
pub fn handler(_: c_int) {
super::DONE.store(true, Ordering::Relaxed);
}
#[cfg(feature = "termination")]
#[inline]
pub unsafe fn set_os_handler(handler: fn(c_int)) {
signal(SIGINT, ::std::mem::transmute::<_, sighandler_t>(handler));
signal(SIGTERM, ::std::mem::transmute::<_, sighandler_t>(handler));
}
#[cfg(not(feature = "termination"))]
#[inline]
pub unsafe fn set_os_handler(handler: fn(c_int)) {
signal(SIGINT, ::std::mem::transmute::<_, sighandler_t>(handler));
}
}
#[cfg(windows)]
mod platform {
extern crate winapi;
extern crate kernel32;
use self::kernel32::SetConsoleCtrlHandler;
use self::winapi::{BOOL, DWORD, TRUE};
use std::sync::atomic::Ordering;
pub unsafe extern "system" fn handler(_: DWORD) -> BOOL {
super::DONE.store(true, Ordering::Relaxed);
TRUE
}
#[inline]
pub unsafe fn set_os_handler(handler: unsafe extern "system" fn(DWORD) -> BOOL) {
SetConsoleCtrlHandler(Some(handler), TRUE);
}
}
use self::platform::*;
pub fn set_handler<F>(user_handler: F)
where F: Fn() -> () + 'static + Send
{
self::set_handler_with_polling_rate(user_handler, time::Duration::from_millis(100));
}
pub fn set_handler_with_polling_rate<F>(user_handler: F, polling_rate: time::Duration)
where F: Fn() -> () + 'static + Send
{
unsafe {
set_os_handler(handler);
}
thread::spawn(move || {
loop {
if DONE.compare_and_swap(true, false, Ordering::Relaxed) {
user_handler();
}
thread::sleep(polling_rate);
}
});
}