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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
use crate::error::Error as CtrlcError;
use nix::unistd;
use std::os::unix::io::RawFd;
static mut PIPE: (RawFd, RawFd) = (-1, -1);
pub type Error = nix::Error;
pub type Signal = nix::sys::signal::Signal;
extern "C" fn os_handler(_: nix::libc::c_int) {
unsafe {
let _ = unistd::write(PIPE.1, &[0u8]);
}
}
#[inline]
#[cfg(any(target_os = "ios", target_os = "macos"))]
fn pipe2(flags: nix::fcntl::OFlag) -> nix::Result<(RawFd, RawFd)> {
use nix::fcntl::{fcntl, FcntlArg, FdFlag, OFlag};
let pipe = unistd::pipe()?;
let mut res = Ok(0);
if flags.contains(OFlag::O_CLOEXEC) {
res = res
.and_then(|_| fcntl(pipe.0, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)))
.and_then(|_| fcntl(pipe.1, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)));
}
if flags.contains(OFlag::O_NONBLOCK) {
res = res
.and_then(|_| fcntl(pipe.0, FcntlArg::F_SETFL(OFlag::O_NONBLOCK)))
.and_then(|_| fcntl(pipe.1, FcntlArg::F_SETFL(OFlag::O_NONBLOCK)));
}
match res {
Ok(_) => Ok(pipe),
Err(e) => {
let _ = unistd::close(pipe.0);
let _ = unistd::close(pipe.1);
Err(e)
}
}
}
#[inline]
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
fn pipe2(flags: nix::fcntl::OFlag) -> nix::Result<(RawFd, RawFd)> {
unistd::pipe2(flags)
}
#[inline]
pub unsafe fn init_os_handler() -> Result<(), Error> {
use nix::fcntl;
use nix::sys::signal;
PIPE = pipe2(fcntl::OFlag::O_CLOEXEC)?;
let close_pipe = |e: nix::Error| -> Error {
let _ = unistd::close(PIPE.1);
let _ = unistd::close(PIPE.0);
e
};
if let Err(e) = fcntl::fcntl(PIPE.1, fcntl::FcntlArg::F_SETFL(fcntl::OFlag::O_NONBLOCK)) {
return Err(close_pipe(e));
}
let handler = signal::SigHandler::Handler(os_handler);
let new_action = signal::SigAction::new(
handler,
signal::SaFlags::SA_RESTART,
signal::SigSet::empty(),
);
let _old = match signal::sigaction(signal::Signal::SIGINT, &new_action) {
Ok(old) => old,
Err(e) => return Err(close_pipe(e)),
};
#[cfg(feature = "termination")]
match signal::sigaction(signal::Signal::SIGTERM, &new_action) {
Ok(_) => {}
Err(e) => {
signal::sigaction(signal::Signal::SIGINT, &_old).unwrap();
return Err(close_pipe(e));
}
}
Ok(())
}
#[inline]
pub unsafe fn block_ctrl_c() -> Result<(), CtrlcError> {
use std::io;
let mut buf = [0u8];
loop {
match unistd::read(PIPE.0, &mut buf[..]) {
Ok(1) => break,
Ok(_) => return Err(CtrlcError::System(io::ErrorKind::UnexpectedEof.into())),
Err(nix::Error::Sys(nix::errno::Errno::EINTR)) => {}
Err(e) => return Err(e.into()),
}
}
Ok(())
}