forked from trifectatechfoundation/sudo-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwait.rs
249 lines (206 loc) · 7.24 KB
/
wait.rs
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
use std::io;
use libc::{
c_int, WEXITSTATUS, WIFCONTINUED, WIFEXITED, WIFSIGNALED, WIFSTOPPED, WNOHANG, WSTOPSIG,
WTERMSIG, WUNTRACED, __WALL,
};
use crate::cutils::cerr;
use crate::system::signal::signal_name;
use crate::{system::interface::ProcessId, system::signal::SignalNumber};
mod sealed {
pub(crate) trait Sealed {}
impl Sealed for crate::system::interface::ProcessId {}
}
pub(crate) trait Wait: sealed::Sealed {
/// Wait for a process to change state.
///
/// Calling this function will block until a child specified by the given process ID has
/// changed state. This can be configured further using [`WaitOptions`].
fn wait(self, options: WaitOptions) -> Result<(ProcessId, WaitStatus), WaitError>;
}
impl Wait for ProcessId {
fn wait(self, options: WaitOptions) -> Result<(ProcessId, WaitStatus), WaitError> {
let mut status: c_int = 0;
let pid = cerr(unsafe { libc::waitpid(self, &mut status, options.flags) })
.map_err(WaitError::Io)?;
if pid == 0 && options.flags & WNOHANG != 0 {
return Err(WaitError::NotReady);
}
Ok((pid, WaitStatus { status }))
}
}
/// Error values returned when [`Wait::wait`] fails.
#[derive(Debug)]
pub enum WaitError {
// No children were in a waitable state.
//
// This is only returned if the [`WaitOptions::no_hang`] option is used.
NotReady,
// Regular I/O error.
Io(io::Error),
}
/// Options to configure how [`Wait::wait`] waits for children.
pub struct WaitOptions {
flags: c_int,
}
impl WaitOptions {
/// Only wait for terminated children.
pub const fn new() -> Self {
Self { flags: 0 }
}
/// Return immediately if no child has exited.
pub const fn no_hang(mut self) -> Self {
self.flags |= WNOHANG;
self
}
/// Return immediately if a child has stopped.
pub const fn untraced(mut self) -> Self {
self.flags |= WUNTRACED;
self
}
/// Wait for all children, regardless of being created using `clone` or not.
pub const fn all(mut self) -> Self {
self.flags |= __WALL;
self
}
}
/// The status of the waited child.
pub struct WaitStatus {
status: c_int,
}
impl std::fmt::Debug for WaitStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(exit_status) = self.exit_status() {
write!(f, "ExitStatus({exit_status})")
} else if let Some(signal) = self.term_signal() {
write!(f, "TermSignal({})", signal_name(signal))
} else if let Some(signal) = self.stop_signal() {
write!(f, "StopSignal({})", signal_name(signal))
} else if self.did_continue() {
write!(f, "Continued")
} else {
write!(f, "Unknown")
}
}
}
impl WaitStatus {
/// Return `true` if the child terminated normally, i.e., by calling `exit`.
pub const fn did_exit(&self) -> bool {
WIFEXITED(self.status)
}
/// Return the exit status of the child if the child terminated normally.
pub const fn exit_status(&self) -> Option<c_int> {
if self.did_exit() {
Some(WEXITSTATUS(self.status))
} else {
None
}
}
/// Return `true` if the child process was terminated by a signal.
pub const fn was_signaled(&self) -> bool {
WIFSIGNALED(self.status)
}
/// Return the signal number which caused the child to terminate if the child was terminated by
/// a signal.
pub const fn term_signal(&self) -> Option<SignalNumber> {
if self.was_signaled() {
Some(WTERMSIG(self.status))
} else {
None
}
}
/// Return `true` if the child process was stopped by a signal.
pub const fn was_stopped(&self) -> bool {
WIFSTOPPED(self.status)
}
/// Return the signal number which caused the child to stop if the child was stopped by a
/// signal.
pub const fn stop_signal(&self) -> Option<SignalNumber> {
if self.was_stopped() {
Some(WSTOPSIG(self.status))
} else {
None
}
}
/// Return `true` if the child process was resumed by receiving `SIGCONT`.
pub const fn did_continue(&self) -> bool {
WIFCONTINUED(self.status)
}
}
#[cfg(test)]
mod tests {
use libc::{SIGKILL, SIGSTOP};
use crate::system::{
interface::ProcessId,
kill,
wait::{Wait, WaitError, WaitOptions},
};
#[test]
fn exit_status() {
let command = std::process::Command::new("sh")
.args(["-c", "sleep 0.1; exit 42"])
.spawn()
.unwrap();
let command_pid = command.id() as ProcessId;
let (pid, status) = command_pid.wait(WaitOptions::new()).unwrap();
assert_eq!(command_pid, pid);
assert!(status.did_exit());
assert_eq!(status.exit_status(), Some(42));
assert!(!status.was_signaled());
assert!(status.term_signal().is_none());
assert!(!status.was_stopped());
assert!(status.stop_signal().is_none());
assert!(!status.did_continue());
// Waiting when there are no children should fail.
let WaitError::Io(err) = command_pid.wait(WaitOptions::new()).unwrap_err() else {
panic!("`WaitError::NotReady` should not happens if `WaitOptions::no_hang` was not called.");
};
assert_eq!(err.raw_os_error(), Some(libc::ECHILD));
}
#[test]
fn signals() {
let command = std::process::Command::new("sh")
.args(["-c", "sleep 1; exit 42"])
.spawn()
.unwrap();
let command_pid = command.id() as ProcessId;
kill(command_pid, SIGSTOP).unwrap();
let (pid, status) = command_pid.wait(WaitOptions::new().untraced()).unwrap();
assert_eq!(command_pid, pid);
assert_eq!(status.stop_signal(), Some(SIGSTOP));
kill(command_pid, SIGKILL).unwrap();
let (pid, status) = command_pid.wait(WaitOptions::new()).unwrap();
assert_eq!(command_pid, pid);
assert!(status.was_signaled());
assert_eq!(status.term_signal(), Some(SIGKILL));
assert!(!status.did_exit());
assert!(status.exit_status().is_none());
assert!(!status.was_stopped());
assert!(status.stop_signal().is_none());
assert!(!status.did_continue());
}
#[test]
fn no_hang() {
let command = std::process::Command::new("sh")
.args(["-c", "sleep 0.1; exit 42"])
.spawn()
.unwrap();
let command_pid = command.id() as ProcessId;
let mut count = 0;
let (pid, status) = loop {
match command_pid.wait(WaitOptions::new().no_hang()) {
Ok(ok) => break ok,
Err(WaitError::NotReady) => count += 1,
Err(WaitError::Io(err)) => panic!("{err}"),
}
};
assert_eq!(command_pid, pid);
assert!(status.did_exit());
assert_eq!(status.exit_status(), Some(42));
assert!(count > 0);
assert!(!status.was_signaled());
assert!(status.term_signal().is_none());
assert!(!status.was_stopped());
assert!(status.stop_signal().is_none());
assert!(!status.did_continue());
}
}