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
#![forbid(missing_docs)]
#[cfg(not(target_os = "linux"))]
compile_error!("pidfd only works on Linux");
use std::io;
use std::mem::MaybeUninit;
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::process::ExitStatusExt;
use std::process::ExitStatus;
#[cfg(feature = "async")]
use async_io::Async;
const SYS_PIDFD_OPEN: libc::c_long = 434;
const P_PIDFD: libc::idtype_t = 3;
const CLD_EXITED: libc::c_int = 1;
fn syscall_result(ret: libc::c_long) -> io::Result<libc::c_long> {
if ret == -1 {
Err(io::Error::last_os_error())
} else {
Ok(ret)
}
}
fn pidfd_open(pid: libc::pid_t, flags: libc::c_uint) -> io::Result<RawFd> {
let ret = syscall_result(unsafe { libc::syscall(SYS_PIDFD_OPEN, pid, flags) })?;
Ok(ret as RawFd)
}
fn waitid_pidfd(pidfd: RawFd) -> io::Result<(libc::siginfo_t, libc::rusage)> {
let mut siginfo = MaybeUninit::uninit();
let mut rusage = MaybeUninit::uninit();
unsafe {
syscall_result(libc::syscall(
libc::SYS_waitid,
P_PIDFD,
pidfd,
siginfo.as_mut_ptr(),
libc::WEXITED,
rusage.as_mut_ptr(),
))?;
Ok((siginfo.assume_init(), rusage.assume_init()))
}
}
pub struct PidFd(RawFd);
impl PidFd {
pub fn from_pid(pid: libc::pid_t) -> io::Result<Self> {
Ok(Self(pidfd_open(pid, 0)?))
}
pub fn wait(&self) -> io::Result<ExitInfo> {
let (siginfo, rusage) = waitid_pidfd(self.0)?;
Ok(ExitInfo { siginfo, rusage })
}
}
impl Drop for PidFd {
fn drop(&mut self) {
unsafe { libc::close(self.0) };
}
}
impl AsRawFd for PidFd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
mod siginfo_accessor {
#[repr(C)]
#[derive(Copy, Clone)]
struct sifields_sigchld {
si_pid: libc::pid_t,
si_uid: libc::uid_t,
si_status: libc::c_int,
}
#[repr(C)]
union sifields {
_align_pointer: *mut libc::c_void,
sigchld: sifields_sigchld,
}
#[repr(C)]
struct siginfo_sifields {
_siginfo_base: [libc::c_int; 3],
sifields: sifields,
}
pub(crate) unsafe fn siginfo_si_status(siginfo: &libc::siginfo_t) -> libc::c_int {
(*(siginfo as *const libc::siginfo_t as *const siginfo_sifields))
.sifields
.sigchld
.si_status
}
}
pub struct ExitInfo {
pub siginfo: libc::siginfo_t,
pub rusage: libc::rusage,
}
impl ExitInfo {
pub fn status(&self) -> ExitStatus {
let si_status = unsafe { siginfo_accessor::siginfo_si_status(&self.siginfo) };
let raw_status = if self.siginfo.si_code == CLD_EXITED {
si_status << 8
} else {
si_status
};
ExitStatus::from_raw(raw_status)
}
}
#[cfg(feature = "async")]
pub struct AsyncPidFd(Async<PidFd>);
#[cfg(feature = "async")]
impl AsyncPidFd {
pub fn from_pid(pid: libc::pid_t) -> io::Result<Self> {
Ok(Self(Async::new(PidFd::from_pid(pid)?)?))
}
pub async fn wait(&self) -> io::Result<ExitInfo> {
self.0.readable().await?;
self.0.get_ref().wait()
}
}
#[cfg(test)]
mod test {
use super::*;
use std::process::Command;
fn spawn_and_status(cmd: &mut Command) -> io::Result<ExitStatus> {
let child = cmd.spawn()?;
let pidfd = PidFd::from_pid(child.id() as libc::pid_t)?;
Ok(pidfd.wait()?.status())
}
#[test]
fn test() -> std::io::Result<()> {
let status = spawn_and_status(&mut Command::new("/bin/true"))?;
assert_eq!(status.code(), Some(0));
assert_eq!(status.signal(), None);
let status = spawn_and_status(&mut Command::new("/bin/false"))?;
assert_eq!(status.code(), Some(1));
assert_eq!(status.signal(), None);
let status = spawn_and_status(Command::new("/bin/sh").arg("-c").arg("kill -9 $$"))?;
assert_eq!(status.code(), None);
assert_eq!(status.signal(), Some(9));
Ok(())
}
fn assert_echild(ret: io::Result<ExitInfo>) {
if let Err(e) = ret {
assert_eq!(e.raw_os_error(), Some(libc::ECHILD));
} else {
panic!("Expected an error!");
}
}
#[test]
fn test_wait_twice() -> std::io::Result<()> {
let child = Command::new("/bin/true").spawn()?;
let pidfd = PidFd::from_pid(child.id() as libc::pid_t)?;
let status = pidfd.wait()?.status();
assert!(status.success());
let ret = pidfd.wait();
assert_echild(ret);
Ok(())
}
#[cfg(feature = "async")]
async fn async_spawn_and_status(cmd: &mut Command) -> io::Result<ExitStatus> {
let child = cmd.spawn()?;
let pidfd = AsyncPidFd::from_pid(child.id() as libc::pid_t)?;
Ok(pidfd.wait().await?.status())
}
#[cfg(feature = "async")]
#[test]
fn test_async() -> std::io::Result<()> {
use futures_lite::future;
future::block_on(async {
let (status1, status2) = future::try_join(
async_spawn_and_status(&mut Command::new("/bin/true")),
async_spawn_and_status(&mut Command::new("/bin/false")),
)
.await?;
assert_eq!(status1.code(), Some(0));
assert_eq!(status2.code(), Some(1));
Ok(())
})
}
#[cfg(feature = "async")]
#[test]
fn test_async_concurrent() -> std::io::Result<()> {
use futures_lite::future::{self, FutureExt};
future::block_on(async {
let status = async_spawn_and_status(
Command::new("/bin/sh")
.arg("-c")
.arg("read line")
.stdin(std::process::Stdio::piped()),
)
.or(async_spawn_and_status(&mut Command::new("/bin/false")))
.await?;
assert_eq!(status.code(), Some(1));
Ok(())
})
}
#[cfg(feature = "async")]
#[test]
fn test_async_wait_twice() -> std::io::Result<()> {
futures_lite::future::block_on(async {
let child = Command::new("/bin/true").spawn()?;
let pidfd = AsyncPidFd::from_pid(child.id() as libc::pid_t)?;
let status = pidfd.wait().await?.status();
assert!(status.success());
let ret = pidfd.wait().await;
assert_echild(ret);
Ok(())
})
}
}