nix/sys/wait.rs
1//! Wait for a process to change status
2use crate::errno::Errno;
3use crate::sys::signal::Signal;
4use crate::unistd::Pid;
5use crate::Result;
6use cfg_if::cfg_if;
7use libc::{self, c_int};
8use std::convert::TryFrom;
9#[cfg(any(
10 target_os = "android",
11 all(target_os = "linux", not(target_env = "uclibc")),
12))]
13use std::os::unix::io::RawFd;
14
15libc_bitflags!(
16 /// Controls the behavior of [`waitpid`].
17 pub struct WaitPidFlag: c_int {
18 /// Do not block when there are no processes wishing to report status.
19 WNOHANG;
20 /// Report the status of selected processes which are stopped due to a
21 /// [`SIGTTIN`](crate::sys::signal::Signal::SIGTTIN),
22 /// [`SIGTTOU`](crate::sys::signal::Signal::SIGTTOU),
23 /// [`SIGTSTP`](crate::sys::signal::Signal::SIGTSTP), or
24 /// [`SIGSTOP`](crate::sys::signal::Signal::SIGSTOP) signal.
25 WUNTRACED;
26 /// Report the status of selected processes which have terminated.
27 #[cfg(any(target_os = "android",
28 target_os = "freebsd",
29 target_os = "haiku",
30 target_os = "ios",
31 target_os = "linux",
32 target_os = "redox",
33 target_os = "macos",
34 target_os = "netbsd"))]
35 #[cfg_attr(docsrs, doc(cfg(all())))]
36 WEXITED;
37 /// Report the status of selected processes that have continued from a
38 /// job control stop by receiving a
39 /// [`SIGCONT`](crate::sys::signal::Signal::SIGCONT) signal.
40 WCONTINUED;
41 /// An alias for WUNTRACED.
42 #[cfg(any(target_os = "android",
43 target_os = "freebsd",
44 target_os = "haiku",
45 target_os = "ios",
46 target_os = "linux",
47 target_os = "redox",
48 target_os = "macos",
49 target_os = "netbsd"))]
50 #[cfg_attr(docsrs, doc(cfg(all())))]
51 WSTOPPED;
52 /// Don't reap, just poll status.
53 #[cfg(any(target_os = "android",
54 target_os = "freebsd",
55 target_os = "haiku",
56 target_os = "ios",
57 target_os = "linux",
58 target_os = "redox",
59 target_os = "macos",
60 target_os = "netbsd"))]
61 #[cfg_attr(docsrs, doc(cfg(all())))]
62 WNOWAIT;
63 /// Don't wait on children of other threads in this group
64 #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))]
65 #[cfg_attr(docsrs, doc(cfg(all())))]
66 __WNOTHREAD;
67 /// Wait on all children, regardless of type
68 #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))]
69 #[cfg_attr(docsrs, doc(cfg(all())))]
70 __WALL;
71 /// Wait for "clone" children only.
72 #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))]
73 #[cfg_attr(docsrs, doc(cfg(all())))]
74 __WCLONE;
75 }
76);
77
78/// Possible return values from `wait()` or `waitpid()`.
79///
80/// Each status (other than `StillAlive`) describes a state transition
81/// in a child process `Pid`, such as the process exiting or stopping,
82/// plus additional data about the transition if any.
83///
84/// Note that there are two Linux-specific enum variants, `PtraceEvent`
85/// and `PtraceSyscall`. Portable code should avoid exhaustively
86/// matching on `WaitStatus`.
87#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
88pub enum WaitStatus {
89 /// The process exited normally (as with `exit()` or returning from
90 /// `main`) with the given exit code. This case matches the C macro
91 /// `WIFEXITED(status)`; the second field is `WEXITSTATUS(status)`.
92 Exited(Pid, i32),
93 /// The process was killed by the given signal. The third field
94 /// indicates whether the signal generated a core dump. This case
95 /// matches the C macro `WIFSIGNALED(status)`; the last two fields
96 /// correspond to `WTERMSIG(status)` and `WCOREDUMP(status)`.
97 Signaled(Pid, Signal, bool),
98 /// The process is alive, but was stopped by the given signal. This
99 /// is only reported if `WaitPidFlag::WUNTRACED` was passed. This
100 /// case matches the C macro `WIFSTOPPED(status)`; the second field
101 /// is `WSTOPSIG(status)`.
102 Stopped(Pid, Signal),
103 /// The traced process was stopped by a `PTRACE_EVENT_*` event. See
104 /// [`nix::sys::ptrace`] and [`ptrace`(2)] for more information. All
105 /// currently-defined events use `SIGTRAP` as the signal; the third
106 /// field is the `PTRACE_EVENT_*` value of the event.
107 ///
108 /// [`nix::sys::ptrace`]: ../ptrace/index.html
109 /// [`ptrace`(2)]: https://man7.org/linux/man-pages/man2/ptrace.2.html
110 #[cfg(any(target_os = "linux", target_os = "android"))]
111 #[cfg_attr(docsrs, doc(cfg(all())))]
112 PtraceEvent(Pid, Signal, c_int),
113 /// The traced process was stopped by execution of a system call,
114 /// and `PTRACE_O_TRACESYSGOOD` is in effect. See [`ptrace`(2)] for
115 /// more information.
116 ///
117 /// [`ptrace`(2)]: https://man7.org/linux/man-pages/man2/ptrace.2.html
118 #[cfg(any(target_os = "linux", target_os = "android"))]
119 #[cfg_attr(docsrs, doc(cfg(all())))]
120 PtraceSyscall(Pid),
121 /// The process was previously stopped but has resumed execution
122 /// after receiving a `SIGCONT` signal. This is only reported if
123 /// `WaitPidFlag::WCONTINUED` was passed. This case matches the C
124 /// macro `WIFCONTINUED(status)`.
125 Continued(Pid),
126 /// There are currently no state changes to report in any awaited
127 /// child process. This is only returned if `WaitPidFlag::WNOHANG`
128 /// was used (otherwise `wait()` or `waitpid()` would block until
129 /// there was something to report).
130 StillAlive,
131}
132
133impl WaitStatus {
134 /// Extracts the PID from the WaitStatus unless it equals StillAlive.
135 pub fn pid(&self) -> Option<Pid> {
136 use self::WaitStatus::*;
137 match *self {
138 Exited(p, _) | Signaled(p, _, _) | Stopped(p, _) | Continued(p) => Some(p),
139 StillAlive => None,
140 #[cfg(any(target_os = "android", target_os = "linux"))]
141 PtraceEvent(p, _, _) | PtraceSyscall(p) => Some(p),
142 }
143 }
144}
145
146fn exited(status: i32) -> bool {
147 libc::WIFEXITED(status)
148}
149
150fn exit_status(status: i32) -> i32 {
151 libc::WEXITSTATUS(status)
152}
153
154fn signaled(status: i32) -> bool {
155 libc::WIFSIGNALED(status)
156}
157
158fn term_signal(status: i32) -> Result<Signal> {
159 Signal::try_from(libc::WTERMSIG(status))
160}
161
162fn dumped_core(status: i32) -> bool {
163 libc::WCOREDUMP(status)
164}
165
166fn stopped(status: i32) -> bool {
167 libc::WIFSTOPPED(status)
168}
169
170fn stop_signal(status: i32) -> Result<Signal> {
171 Signal::try_from(libc::WSTOPSIG(status))
172}
173
174#[cfg(any(target_os = "android", target_os = "linux"))]
175fn syscall_stop(status: i32) -> bool {
176 // From ptrace(2), setting PTRACE_O_TRACESYSGOOD has the effect
177 // of delivering SIGTRAP | 0x80 as the signal number for syscall
178 // stops. This allows easily distinguishing syscall stops from
179 // genuine SIGTRAP signals.
180 libc::WSTOPSIG(status) == libc::SIGTRAP | 0x80
181}
182
183#[cfg(any(target_os = "android", target_os = "linux"))]
184fn stop_additional(status: i32) -> c_int {
185 (status >> 16) as c_int
186}
187
188fn continued(status: i32) -> bool {
189 libc::WIFCONTINUED(status)
190}
191
192impl WaitStatus {
193 /// Convert a raw `wstatus` as returned by `waitpid`/`wait` into a `WaitStatus`
194 ///
195 /// # Errors
196 ///
197 /// Returns an `Error` corresponding to `EINVAL` for invalid status values.
198 ///
199 /// # Examples
200 ///
201 /// Convert a `wstatus` obtained from `libc::waitpid` into a `WaitStatus`:
202 ///
203 /// ```
204 /// use nix::sys::wait::WaitStatus;
205 /// use nix::sys::signal::Signal;
206 /// let pid = nix::unistd::Pid::from_raw(1);
207 /// let status = WaitStatus::from_raw(pid, 0x0002);
208 /// assert_eq!(status, Ok(WaitStatus::Signaled(pid, Signal::SIGINT, false)));
209 /// ```
210 pub fn from_raw(pid: Pid, status: i32) -> Result<WaitStatus> {
211 Ok(if exited(status) {
212 WaitStatus::Exited(pid, exit_status(status))
213 } else if signaled(status) {
214 WaitStatus::Signaled(pid, term_signal(status)?, dumped_core(status))
215 } else if stopped(status) {
216 cfg_if! {
217 if #[cfg(any(target_os = "android", target_os = "linux"))] {
218 fn decode_stopped(pid: Pid, status: i32) -> Result<WaitStatus> {
219 let status_additional = stop_additional(status);
220 Ok(if syscall_stop(status) {
221 WaitStatus::PtraceSyscall(pid)
222 } else if status_additional == 0 {
223 WaitStatus::Stopped(pid, stop_signal(status)?)
224 } else {
225 WaitStatus::PtraceEvent(pid, stop_signal(status)?,
226 stop_additional(status))
227 })
228 }
229 } else {
230 fn decode_stopped(pid: Pid, status: i32) -> Result<WaitStatus> {
231 Ok(WaitStatus::Stopped(pid, stop_signal(status)?))
232 }
233 }
234 }
235 return decode_stopped(pid, status);
236 } else {
237 assert!(continued(status));
238 WaitStatus::Continued(pid)
239 })
240 }
241
242 /// Convert a `siginfo_t` as returned by `waitid` to a `WaitStatus`
243 ///
244 /// # Errors
245 ///
246 /// Returns an `Error` corresponding to `EINVAL` for invalid values.
247 ///
248 /// # Safety
249 ///
250 /// siginfo_t is actually a union, not all fields may be initialized.
251 /// The functions si_pid() and si_status() must be valid to call on
252 /// the passed siginfo_t.
253 #[cfg(any(
254 target_os = "android",
255 target_os = "freebsd",
256 target_os = "haiku",
257 all(target_os = "linux", not(target_env = "uclibc")),
258 ))]
259 unsafe fn from_siginfo(siginfo: &libc::siginfo_t) -> Result<WaitStatus> {
260 let si_pid = siginfo.si_pid();
261 if si_pid == 0 {
262 return Ok(WaitStatus::StillAlive);
263 }
264
265 assert_eq!(siginfo.si_signo, libc::SIGCHLD);
266
267 let pid = Pid::from_raw(si_pid);
268 let si_status = siginfo.si_status();
269
270 let status = match siginfo.si_code {
271 libc::CLD_EXITED => WaitStatus::Exited(pid, si_status),
272 libc::CLD_KILLED | libc::CLD_DUMPED => WaitStatus::Signaled(
273 pid,
274 Signal::try_from(si_status)?,
275 siginfo.si_code == libc::CLD_DUMPED,
276 ),
277 libc::CLD_STOPPED => WaitStatus::Stopped(pid, Signal::try_from(si_status)?),
278 libc::CLD_CONTINUED => WaitStatus::Continued(pid),
279 #[cfg(any(target_os = "android", target_os = "linux"))]
280 libc::CLD_TRAPPED => {
281 if si_status == libc::SIGTRAP | 0x80 {
282 WaitStatus::PtraceSyscall(pid)
283 } else {
284 WaitStatus::PtraceEvent(
285 pid,
286 Signal::try_from(si_status & 0xff)?,
287 (si_status >> 8) as c_int,
288 )
289 }
290 }
291 _ => return Err(Errno::EINVAL),
292 };
293
294 Ok(status)
295 }
296}
297
298/// Wait for a process to change status
299///
300/// See also [waitpid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/waitpid.html)
301pub fn waitpid<P: Into<Option<Pid>>>(pid: P, options: Option<WaitPidFlag>) -> Result<WaitStatus> {
302 use self::WaitStatus::*;
303
304 let mut status: i32 = 0;
305
306 let option_bits = match options {
307 Some(bits) => bits.bits(),
308 None => 0,
309 };
310
311 let res = unsafe {
312 libc::waitpid(
313 pid.into().unwrap_or_else(|| Pid::from_raw(-1)).into(),
314 &mut status as *mut c_int,
315 option_bits,
316 )
317 };
318
319 match Errno::result(res)? {
320 0 => Ok(StillAlive),
321 res => WaitStatus::from_raw(Pid::from_raw(res), status),
322 }
323}
324
325/// Wait for any child process to change status or a signal is received.
326///
327/// See also [wait(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html)
328pub fn wait() -> Result<WaitStatus> {
329 waitpid(None, None)
330}
331
332/// The ID argument for `waitid`
333#[cfg(any(
334 target_os = "android",
335 target_os = "freebsd",
336 target_os = "haiku",
337 all(target_os = "linux", not(target_env = "uclibc")),
338))]
339#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
340pub enum Id {
341 /// Wait for any child
342 All,
343 /// Wait for the child whose process ID matches the given PID
344 Pid(Pid),
345 /// Wait for the child whose process group ID matches the given PID
346 ///
347 /// If the PID is zero, the caller's process group is used since Linux 5.4.
348 PGid(Pid),
349 /// Wait for the child referred to by the given PID file descriptor
350 #[cfg(any(target_os = "android", target_os = "linux"))]
351 PIDFd(RawFd),
352}
353
354/// Wait for a process to change status
355///
356/// See also [waitid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/waitid.html)
357#[cfg(any(
358 target_os = "android",
359 target_os = "freebsd",
360 target_os = "haiku",
361 all(target_os = "linux", not(target_env = "uclibc")),
362))]
363pub fn waitid(id: Id, flags: WaitPidFlag) -> Result<WaitStatus> {
364 let (idtype, idval) = match id {
365 Id::All => (libc::P_ALL, 0),
366 Id::Pid(pid) => (libc::P_PID, pid.as_raw() as libc::id_t),
367 Id::PGid(pid) => (libc::P_PGID, pid.as_raw() as libc::id_t),
368 #[cfg(any(target_os = "android", target_os = "linux"))]
369 Id::PIDFd(fd) => (libc::P_PIDFD, fd as libc::id_t),
370 };
371
372 let siginfo = unsafe {
373 // Memory is zeroed rather than uninitialized, as not all platforms
374 // initialize the memory in the StillAlive case
375 let mut siginfo: libc::siginfo_t = std::mem::zeroed();
376 Errno::result(libc::waitid(idtype, idval, &mut siginfo, flags.bits()))?;
377 siginfo
378 };
379
380 unsafe { WaitStatus::from_siginfo(&siginfo) }
381}