| 1 | use std::ffi::c_int; |
| 2 | use std::io; |
| 3 | |
| 4 | #[cfg(target_os = "linux")] |
| 5 | use libc::__WALL; |
| 6 | use libc::{ |
| 7 | WEXITSTATUS, WIFCONTINUED, WIFEXITED, WIFSIGNALED, WIFSTOPPED, WNOHANG, WSTOPSIG, WTERMSIG, |
| 8 | WUNTRACED, |
| 9 | }; |
| 10 | |
| 11 | use crate::cutils::cerr; |
| 12 | use crate::system::signal::signal_name; |
| 13 | use crate::{system::interface::ProcessId, system::signal::SignalNumber}; |
| 14 | |
| 15 | #[cfg(not(target_os = "linux"))] |
| 16 | const __WALL: c_int = 0; |
| 17 | |
| 18 | mod sealed { |
| 19 | pub(crate) trait Sealed {} |
| 20 | |
| 21 | impl Sealed for crate::system::interface::ProcessId {} |
| 22 | } |
| 23 | |
| 24 | pub(crate) trait Wait: sealed::Sealed { |
| 25 | /// Wait for a process to change state. |
| 26 | /// |
| 27 | /// Calling this function will block until a child specified by the given process ID has |
| 28 | /// changed state. This can be configured further using [`WaitOptions`]. |
| 29 | fn wait(self, options: WaitOptions) -> Result<(ProcessId, WaitStatus), WaitError>; |
| 30 | } |
| 31 | |
| 32 | impl Wait for ProcessId { |
| 33 | fn wait(self, options: WaitOptions) -> Result<(ProcessId, WaitStatus), WaitError> { |
| 34 | let mut status: c_int = 0; |
| 35 | |
| 36 | // SAFETY: a valid pointer is passed to `waitpid` |
| 37 | let pid = cerr(unsafe { libc::waitpid(self.inner(), &mut status, options.flags) }) |
| 38 | .map_err(WaitError::Io)?; |
| 39 | |
| 40 | if pid == 0 && options.flags & WNOHANG != 0 { |
| 41 | return Err(WaitError::NotReady); |
| 42 | } |
| 43 | |
| 44 | Ok((ProcessId::new(pid), WaitStatus { status })) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | /// Error values returned when [`Wait::wait`] fails. |
| 49 | #[derive(Debug)] |
| 50 | pub enum WaitError { |
| 51 | // No children were in a waitable state. |
| 52 | // |
| 53 | // This is only returned if the [`WaitOptions::no_hang`] option is used. |
| 54 | NotReady, |
| 55 | // Regular I/O error. |
| 56 | Io(io::Error), |
| 57 | } |
| 58 | |
| 59 | /// Options to configure how [`Wait::wait`] waits for children. |
| 60 | pub struct WaitOptions { |
| 61 | flags: c_int, |
| 62 | } |
| 63 | |
| 64 | impl WaitOptions { |
| 65 | /// Only wait for terminated children. |
| 66 | pub const fn new() -> Self { |
| 67 | Self { flags: 0 } |
| 68 | } |
| 69 | |
| 70 | /// Return immediately if no child has exited. |
| 71 | pub const fn no_hang(mut self) -> Self { |
| 72 | self.flags |= WNOHANG; |
| 73 | self |
| 74 | } |
| 75 | |
| 76 | /// Return immediately if a child has stopped. |
| 77 | pub const fn untraced(mut self) -> Self { |
| 78 | self.flags |= WUNTRACED; |
| 79 | self |
| 80 | } |
| 81 | |
| 82 | /// Wait for all children, regardless of being created using `clone` or not. |
| 83 | pub const fn all(mut self) -> Self { |
| 84 | self.flags |= __WALL; |
| 85 | self |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | /// The status of the waited child. |
| 90 | pub struct WaitStatus { |
| 91 | status: c_int, |
| 92 | } |
| 93 | |
| 94 | impl std::fmt::Debug for WaitStatus { |
| 95 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 96 | if let Some(exit_status) = self.exit_status() { |
| 97 | write!(f, "ExitStatus({exit_status})") |
| 98 | } else if let Some(signal) = self.term_signal() { |
| 99 | write!(f, "TermSignal({})", signal_name(signal)) |
| 100 | } else if let Some(signal) = self.stop_signal() { |
| 101 | write!(f, "StopSignal({})", signal_name(signal)) |
| 102 | } else if self.did_continue() { |
| 103 | write!(f, "Continued") |
| 104 | } else { |
| 105 | write!(f, "Unknown") |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | impl WaitStatus { |
| 111 | /// Return `true` if the child terminated normally, i.e., by calling `exit`. |
| 112 | pub const fn did_exit(&self) -> bool { |
| 113 | WIFEXITED(self.status) |
| 114 | } |
| 115 | |
| 116 | /// Return the exit status of the child if the child terminated normally. |
| 117 | pub const fn exit_status(&self) -> Option<c_int> { |
| 118 | if self.did_exit() { |
| 119 | Some(WEXITSTATUS(self.status)) |
| 120 | } else { |
| 121 | None |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | /// Return `true` if the child process was terminated by a signal. |
| 126 | pub const fn was_signaled(&self) -> bool { |
| 127 | WIFSIGNALED(self.status) |
| 128 | } |
| 129 | |
| 130 | /// Return the signal number which caused the child to terminate if the child was terminated by |
| 131 | /// a signal. |
| 132 | pub const fn term_signal(&self) -> Option<SignalNumber> { |
| 133 | if self.was_signaled() { |
| 134 | Some(WTERMSIG(self.status)) |
| 135 | } else { |
| 136 | None |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /// Return `true` if the child process was stopped by a signal. |
| 141 | pub const fn was_stopped(&self) -> bool { |
| 142 | WIFSTOPPED(self.status) |
| 143 | } |
| 144 | |
| 145 | /// Return the signal number which caused the child to stop if the child was stopped by a |
| 146 | /// signal. |
| 147 | pub const fn stop_signal(&self) -> Option<SignalNumber> { |
| 148 | if self.was_stopped() { |
| 149 | Some(WSTOPSIG(self.status)) |
| 150 | } else { |
| 151 | None |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /// Return `true` if the child process was resumed by receiving `SIGCONT`. |
| 156 | pub const fn did_continue(&self) -> bool { |
| 157 | WIFCONTINUED(self.status) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | #[cfg(test)] |
| 162 | mod tests { |
| 163 | use libc::{SIGKILL, SIGSTOP}; |
| 164 | |
| 165 | use crate::system::{ |
| 166 | interface::ProcessId, |
| 167 | kill, |
| 168 | wait::{Wait, WaitError, WaitOptions}, |
| 169 | }; |
| 170 | |
| 171 | #[test] |
| 172 | fn exit_status() { |
| 173 | #[allow(clippy::zombie_processes)] |
| 174 | let command = std::process::Command::new("sh") |
| 175 | .args(["-c", "sleep 0.1; exit 42"]) |
| 176 | .spawn() |
| 177 | .unwrap(); |
| 178 | |
| 179 | let command_pid = ProcessId::new(command.id() as i32); |
| 180 | |
| 181 | let (pid, status) = command_pid.wait(WaitOptions::new()).unwrap(); |
| 182 | assert_eq!(command_pid, pid); |
| 183 | assert!(status.did_exit()); |
| 184 | assert_eq!(status.exit_status(), Some(42)); |
| 185 | |
| 186 | assert!(!status.was_signaled()); |
| 187 | assert!(status.term_signal().is_none()); |
| 188 | assert!(!status.was_stopped()); |
| 189 | assert!(status.stop_signal().is_none()); |
| 190 | assert!(!status.did_continue()); |
| 191 | |
| 192 | // Waiting when there are no children should fail. |
| 193 | let WaitError::Io(err) = command_pid.wait(WaitOptions::new()).unwrap_err() else { |
| 194 | panic!( |
| 195 | "`WaitError::NotReady` should not happens if `WaitOptions::no_hang` was not called." |
| 196 | ); |
| 197 | }; |
| 198 | assert_eq!(err.raw_os_error(), Some(libc::ECHILD)); |
| 199 | } |
| 200 | |
| 201 | #[test] |
| 202 | fn signals() { |
| 203 | #[allow(clippy::zombie_processes)] |
| 204 | let command = std::process::Command::new("sh") |
| 205 | .args(["-c", "sleep 1; exit 42"]) |
| 206 | .spawn() |
| 207 | .unwrap(); |
| 208 | |
| 209 | let command_pid = ProcessId::new(command.id() as i32); |
| 210 | |
| 211 | kill(command_pid, SIGSTOP).unwrap(); |
| 212 | |
| 213 | let (pid, status) = command_pid.wait(WaitOptions::new().untraced()).unwrap(); |
| 214 | assert_eq!(command_pid, pid); |
| 215 | assert_eq!(status.stop_signal(), Some(SIGSTOP)); |
| 216 | |
| 217 | kill(command_pid, SIGKILL).unwrap(); |
| 218 | |
| 219 | let (pid, status) = command_pid.wait(WaitOptions::new()).unwrap(); |
| 220 | assert_eq!(command_pid, pid); |
| 221 | assert!(status.was_signaled()); |
| 222 | assert_eq!(status.term_signal(), Some(SIGKILL)); |
| 223 | |
| 224 | assert!(!status.did_exit()); |
| 225 | assert!(status.exit_status().is_none()); |
| 226 | assert!(!status.was_stopped()); |
| 227 | assert!(status.stop_signal().is_none()); |
| 228 | assert!(!status.did_continue()); |
| 229 | } |
| 230 | |
| 231 | #[test] |
| 232 | fn no_hang() { |
| 233 | #[allow(clippy::zombie_processes)] |
| 234 | let command = std::process::Command::new("sh") |
| 235 | .args(["-c", "sleep 0.1; exit 42"]) |
| 236 | .spawn() |
| 237 | .unwrap(); |
| 238 | |
| 239 | let command_pid = ProcessId::new(command.id() as i32); |
| 240 | |
| 241 | let mut count = 0; |
| 242 | let (pid, status) = loop { |
| 243 | match command_pid.wait(WaitOptions::new().no_hang()) { |
| 244 | Ok(ok) => break ok, |
| 245 | Err(WaitError::NotReady) => count += 1, |
| 246 | Err(WaitError::Io(err)) => panic!("{err}"), |
| 247 | } |
| 248 | }; |
| 249 | |
| 250 | assert_eq!(command_pid, pid); |
| 251 | assert!(status.did_exit()); |
| 252 | assert_eq!(status.exit_status(), Some(42)); |
| 253 | assert!(count > 0); |
| 254 | |
| 255 | assert!(!status.was_signaled()); |
| 256 | assert!(status.term_signal().is_none()); |
| 257 | assert!(!status.was_stopped()); |
| 258 | assert!(status.stop_signal().is_none()); |
| 259 | assert!(!status.did_continue()); |
| 260 | } |
| 261 | } |