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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
use libc::{c_int, c_uint, pid_t, siginfo_t};
use mio::event::Source;
use mio::unix::SourceFd;
use mio::{Interest, Registry, Token};
use std::convert::TryInto;
use std::io;
use std::os::unix::io::{AsRawFd, RawFd};
use std::process::Child;
use std::ptr;
#[cfg(not(target_os = "linux"))]
compile_error!("pidfd is a linux specific feature");
const NR_PIDFD_OPEN: c_int = 434;
const NR_PIDFD_SEND_SIGNAL: c_int = 424;
extern "C" {
fn syscall(num: c_int, ...) -> c_int;
}
unsafe fn pidfd_create(pid: pid_t, flags: c_uint) -> c_int {
syscall(NR_PIDFD_OPEN, pid, flags)
}
unsafe fn pidfd_send_signal(
pidfd: c_int,
sig: c_int,
info: *const siginfo_t,
flags: c_uint,
) -> c_int {
syscall(NR_PIDFD_SEND_SIGNAL, pidfd, sig, info, flags)
}
pub struct PidFd {
fd: c_int,
}
impl PidFd {
pub fn new(child: &Child) -> io::Result<Self> {
let flags = 0;
let pid: pid_t = match child.id().try_into() {
Ok(pid) => pid,
Err(_) => {
return Err(io::Error::new(
io::ErrorKind::Other,
"child process id outside range of pid_t",
))
}
};
Self::open(pid, flags)
}
pub fn kill(&self, sig: c_int) -> io::Result<()> {
self.send_signal(sig, None, 0)
}
pub fn open(pid: pid_t, flags: c_uint) -> io::Result<Self> {
let fd = unsafe { pidfd_create(pid, flags) };
if fd == -1 {
Err(io::Error::last_os_error())
} else {
Ok(Self { fd })
}
}
pub fn send_signal(&self, sig: c_int, info: Option<&siginfo_t>, flags: c_uint) -> io::Result<()> {
let info = info.map_or_else(ptr::null, |info| info);
let ret = unsafe { pidfd_send_signal(self.fd, sig, info, flags) };
if ret == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
}
impl AsRawFd for PidFd {
fn as_raw_fd(&self) -> RawFd {
self.fd
}
}
impl Drop for PidFd {
fn drop(&mut self) {
let _ = unsafe { libc::close(self.fd) };
}
}
impl Source for PidFd {
fn register(
&mut self,
registry: &Registry,
token: Token,
interest: Interest,
) -> io::Result<()> {
SourceFd(&self.fd).register(registry, token, interest)
}
fn reregister(
&mut self,
registry: &Registry,
token: Token,
interest: Interest,
) -> io::Result<()> {
SourceFd(&self.fd).reregister(registry, token, interest)
}
fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
SourceFd(&self.fd).deregister(registry)
}
}
#[cfg(test)]
mod tests {
use super::*;
use mio::{Events, Poll};
use std::os::unix::process::ExitStatusExt;
use std::process::Command;
use std::time::Duration;
const TOK1: Token = Token(1);
const TOK2: Token = Token(2);
const TIMEOUT1: Duration = Duration::from_secs(1);
const TIMEOUT2: Duration = Duration::from_secs(2);
#[test]
fn pidfd_new_and_kill() {
let sig = libc::SIGABRT;
let mut child = Command::new("/bin/sleep").arg("5").spawn().unwrap();
let fd = PidFd::new(&child).unwrap();
fd.kill(sig).unwrap();
assert!(child.wait().unwrap().signal().unwrap() == sig);
}
#[test]
#[should_panic]
fn pidfd_open_invalid_pid() {
PidFd::open(-1, 0).unwrap();
}
#[test]
#[should_panic]
fn pidfd_kill_invalid_signal() {
let sig = -1;
let child = Command::new("/bin/sleep").arg("0").spawn().unwrap();
let fd = PidFd::new(&child).unwrap();
fd.kill(sig).unwrap();
}
fn create_sleeper(poll: &Poll, timeout: Duration, token: Token) -> (Child, PidFd) {
let child = Command::new("/bin/sleep")
.arg(format!("{}", timeout.as_secs()))
.spawn()
.unwrap();
let mut pidfd = PidFd::new(&child).unwrap();
poll.registry()
.register(&mut pidfd, token, Interest::READABLE)
.unwrap();
return (child, pidfd);
}
#[test]
fn single_process() {
let mut poll = Poll::new().unwrap();
let mut events = Events::with_capacity(1024);
let (mut child, _pidfd) = create_sleeper(&poll, TIMEOUT2, TOK2);
poll.poll(&mut events, Some(TIMEOUT2 / 2)).unwrap();
assert!(events.is_empty());
match child.try_wait() {
Ok(None) => {}
Ok(Some(status)) => {
panic!("child exited without poll event: {}", status);
}
Err(e) => panic!("child error without poll event: {}", e),
}
poll.poll(&mut events, Some(TIMEOUT2)).unwrap();
assert!(!events.is_empty());
match child.try_wait() {
Ok(Some(_)) => {}
Ok(None) => panic!("poll event occured but child has not exited"),
Err(e) => panic!("child error without poll event: {}", e),
}
poll.poll(&mut events, Some(Duration::from_nanos(1)))
.unwrap();
assert!(events.is_empty());
}
#[test]
fn multi_process() {
let mut poll = Poll::new().unwrap();
let mut events = Events::with_capacity(1024);
let (mut child1, _pidfd1) = create_sleeper(&poll, TIMEOUT1, TOK1);
let (mut child2, _pidfd2) = create_sleeper(&poll, TIMEOUT2, TOK2);
poll.poll(&mut events, Some(TIMEOUT1 / 2)).unwrap();
assert!(events.is_empty());
match child1.try_wait() {
Ok(None) => {}
Ok(Some(status)) => panic!("child1 exited without poll event: {}", status),
Err(e) => panic!("child1 error without poll event: {}", e),
}
match child2.try_wait() {
Ok(None) => {}
Ok(Some(status)) => panic!("child2 exited without poll event: {}", status),
Err(e) => panic!("child2 error without poll event: {}", e),
}
poll.poll(&mut events, Some(TIMEOUT1)).unwrap();
assert!(!events.is_empty());
for event in events.iter() {
assert!(event.token() == TOK1);
}
match child1.try_wait() {
Ok(Some(_)) => {}
Ok(None) => panic!("poll event occured but child1 has not exited"),
Err(e) => panic!("child1 error without poll event: {}", e),
}
poll.poll(&mut events, Some(TIMEOUT2)).unwrap();
assert!(!events.is_empty());
for event in events.iter() {
assert!(event.token() == TOK2);
}
match child2.try_wait() {
Ok(Some(_)) => {}
Ok(None) => panic!("poll event occured but child2 has not exited"),
Err(e) => panic!("child2 error without poll event: {}", e),
}
poll.poll(&mut events, Some(Duration::from_nanos(1)))
.unwrap();
assert!(events.is_empty());
}
}