aria_primitives/process/
child.rs1use std::io;
4use std::os::unix::process::CommandExt;
5use std::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus};
6use std::thread;
7use std::time::Instant;
8
9use rustix::io::Errno;
10use rustix::process::{Pid, Signal, kill_process_group};
11
12use super::POLL_INTERVAL;
13
14pub struct ChildProcess {
15 child: Option<Child>,
16 exit_status: Option<ExitStatus>,
18 process_group: u32,
19 owns_process_group: bool,
20}
21
22impl ChildProcess {
23 #[allow(clippy::disallowed_methods)]
25 pub fn spawn(command: &mut Command) -> io::Result<Self> {
26 command.process_group(0);
27 command.spawn().map(|child| {
28 let process_group = child.id();
29 Self {
30 child: Some(child),
31 exit_status: None,
32 process_group,
33 owns_process_group: true,
34 }
35 })
36 }
37
38 pub fn take_stdin(&mut self) -> Option<ChildStdin> {
39 self.child.as_mut()?.stdin.take()
40 }
41
42 pub fn take_stdout(&mut self) -> Option<ChildStdout> {
43 self.child.as_mut()?.stdout.take()
44 }
45
46 pub fn take_stderr(&mut self) -> Option<ChildStderr> {
47 self.child.as_mut()?.stderr.take()
48 }
49
50 pub fn wait_until(
51 &mut self,
52 deadline: Instant,
53 mut should_cancel: impl FnMut() -> bool,
54 ) -> Result<WaitOutcome, ChildProcessError> {
55 loop {
56 if let Some(status) = self.try_wait()? {
57 self.terminate_group()?;
58 return Ok(WaitOutcome::Exited(status));
59 }
60 if should_cancel() {
61 return Ok(WaitOutcome::Cancelled);
62 }
63 if Instant::now() >= deadline {
64 return Ok(WaitOutcome::TimedOut);
65 }
66 thread::sleep(POLL_INTERVAL);
67 }
68 }
69
70 #[cfg(target_os = "macos")]
71 pub fn terminate(mut self) -> Result<(), ChildProcessError> {
72 self.terminate_inner()
73 }
74
75 pub fn terminate_in_place(&mut self) -> Result<(), ChildProcessError> {
78 self.terminate_inner()
79 }
80
81 fn terminate_inner(&mut self) -> Result<(), ChildProcessError> {
82 if self.child.is_none() {
83 return self.terminate_group();
84 }
85 let inspect_error = match self.try_wait() {
86 Ok(Some(_status)) => {
87 self.terminate_group()?;
88 return Ok(());
89 }
90 Ok(None) => None,
91 Err(ChildProcessError::Inspect(source)) => Some(source),
92 Err(error) => return Err(error),
93 };
94
95 if let Err(group_error) = self.terminate_group() {
96 if let Some(_status) = self.try_wait()? {
97 return Err(group_error);
98 }
99 if let Err(source) = self.child_mut()?.kill() {
100 if let Some(_status) = self.try_wait()? {
101 return Err(group_error);
102 }
103 return Err(ChildProcessError::TerminateProcess(source));
104 }
105 self.reap()?;
106 return Err(group_error);
107 }
108 self.reap()?;
109
110 if let Some(source) = inspect_error {
111 return Err(ChildProcessError::Inspect(source));
112 }
113 Ok(())
114 }
115
116 pub fn try_wait(&mut self) -> Result<Option<ExitStatus>, ChildProcessError> {
117 let Some(child) = self.child.as_mut() else {
118 return Ok(self.exit_status);
119 };
120 let status = child.try_wait().map_err(ChildProcessError::Inspect)?;
121 if status.is_some() {
122 self.child = None;
123 self.exit_status = status;
124 }
125 Ok(status)
126 }
127
128 fn reap(&mut self) -> Result<(), ChildProcessError> {
129 let status = self.child_mut()?.wait().map_err(ChildProcessError::Reap)?;
130 self.child = None;
131 self.exit_status = Some(status);
132 Ok(())
133 }
134
135 pub fn request_termination(&self) -> Result<(), ChildProcessError> {
139 if !self.owns_process_group {
140 return Ok(());
141 }
142 self.signal_group(Signal::TERM)
143 }
144
145 fn terminate_group(&mut self) -> Result<(), ChildProcessError> {
146 if !self.owns_process_group {
147 return Ok(());
148 }
149
150 self.signal_group(Signal::KILL)?;
151 self.owns_process_group = false;
152 Ok(())
153 }
154
155 fn signal_group(&self, signal: Signal) -> Result<(), ChildProcessError> {
157 match kill_process_group(self.group_pid()?, signal) {
158 Ok(()) | Err(Errno::SRCH) => Ok(()),
159 #[cfg(target_os = "macos")]
163 Err(Errno::PERM) if self.child_exited()? => Ok(()),
164 Err(source) => Err(ChildProcessError::TerminateGroup(source.into())),
165 }
166 }
167
168 #[cfg(target_os = "macos")]
171 fn child_exited(&self) -> Result<bool, ChildProcessError> {
172 use rustix::process::{WaitId, WaitIdOptions, waitid};
173
174 let Some(child) = &self.child else {
175 return Ok(true);
176 };
177 let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT;
178 waitid(WaitId::Pid(Pid::from_child(child)), options)
179 .map(|status| status.is_some())
180 .map_err(|source| ChildProcessError::Inspect(source.into()))
181 }
182
183 fn group_pid(&self) -> Result<Pid, ChildProcessError> {
184 let raw_pid = i32::try_from(self.process_group)
185 .map_err(|_error| io::Error::other("child process identifier is out of range"))
186 .map_err(ChildProcessError::TerminateGroup)?;
187 Pid::from_raw(raw_pid)
188 .ok_or_else(|| io::Error::other("child process identifier is invalid"))
189 .map_err(ChildProcessError::TerminateGroup)
190 }
191
192 fn child_mut(&mut self) -> Result<&mut Child, ChildProcessError> {
193 self.child.as_mut().ok_or(ChildProcessError::MissingChild)
194 }
195}
196
197impl Drop for ChildProcess {
198 fn drop(&mut self) {
199 if (self.child.is_some() || self.owns_process_group)
200 && let Err(error) = self.terminate_inner()
201 {
202 tracing::error!(?error, "failed to clean up child process before drop");
203 }
204 }
205}
206
207pub enum WaitOutcome {
208 Exited(ExitStatus),
209 Cancelled,
210 TimedOut,
211}
212
213#[derive(Debug, thiserror::Error)]
214pub enum ChildProcessError {
215 #[error("child process ownership ended before cleanup completed")]
216 MissingChild,
217
218 #[error("failed to inspect the child process")]
219 Inspect(#[source] io::Error),
220
221 #[error("failed to terminate the child process group")]
222 TerminateGroup(#[source] io::Error),
223
224 #[error("failed to terminate the child process")]
225 TerminateProcess(#[source] io::Error),
226
227 #[error("failed to reap the child process")]
228 Reap(#[source] io::Error),
229}
230
231#[cfg(test)]
232mod tests {
233 use std::io::{BufRead, BufReader};
234 use std::process::Stdio;
235 use std::thread;
236 use std::time::{Duration, Instant};
237
238 use rustix::process::{WaitId, WaitIdOptions, test_kill_process, waitid};
239
240 use super::super::POLL_INTERVAL;
241 use super::*;
242
243 const PATIENCE: Duration = Duration::from_secs(5);
244
245 fn shell(script: &str) -> Command {
246 let mut command = Command::new("/bin/sh");
247 command.arg("-c").arg(script);
248 command
249 }
250
251 fn spawn(script: &str) -> ChildProcess {
252 ChildProcess::spawn(&mut shell(script)).expect("the shell should start")
253 }
254
255 fn spawn_group() -> (ChildProcess, Pid) {
258 let mut command = shell("sleep 300 & echo $!");
259 command.stdout(Stdio::piped());
260 let mut process = ChildProcess::spawn(&mut command).expect("the shell should start");
261
262 let stdout = process.take_stdout().expect("stdout should be piped");
263 let mut line = String::new();
264 BufReader::new(stdout)
265 .read_line(&mut line)
266 .expect("the shell should report its child");
267 let raw = line.trim().parse().expect("the report should be a pid");
268
269 (
270 process,
271 Pid::from_raw(raw).expect("the pid should be valid"),
272 )
273 }
274
275 fn eventually(mut condition: impl FnMut() -> bool) -> bool {
278 let deadline = Instant::now() + PATIENCE;
279 while Instant::now() < deadline {
280 if condition() {
281 return true;
282 }
283 thread::sleep(POLL_INTERVAL);
284 }
285 false
286 }
287
288 fn gone(pid: Pid) -> bool {
289 eventually(|| test_kill_process(pid).is_err())
290 }
291
292 fn exited(process: &mut ChildProcess) -> bool {
293 eventually(|| {
294 process
295 .try_wait()
296 .expect("inspection should succeed")
297 .is_some()
298 })
299 }
300
301 #[test]
302 fn dropping_a_process_kills_its_whole_group() {
303 let (process, grandchild) = spawn_group();
304
305 drop(process);
306
307 assert!(gone(grandchild), "the grandchild outlived its group");
308 }
309
310 #[test]
311 fn terminating_kills_the_whole_group() {
312 let (mut process, grandchild) = spawn_group();
313
314 process
315 .terminate_in_place()
316 .expect("cleanup should succeed");
317
318 assert!(gone(grandchild), "the grandchild outlived its group");
319 }
320
321 #[test]
322 fn cleanup_succeeds_once_the_child_has_exited() {
323 let mut process = spawn("exit 0");
324 assert!(exited(&mut process), "the shell should exit on its own");
325
326 process
327 .terminate_in_place()
328 .expect("cleanup should succeed");
329 }
330
331 #[test]
332 fn cleanup_succeeds_when_the_child_died_after_the_last_check() {
333 let mut process = spawn("exit 0");
334 let leader = process.group_pid().expect("the pid should be valid");
335 waitid(
336 WaitId::Pid(leader),
337 WaitIdOptions::EXITED | WaitIdOptions::NOWAIT,
338 )
339 .expect("the shell should exit");
340
341 process
342 .terminate_group()
343 .expect("a group of exited processes is already gone");
344 }
345
346 #[test]
347 fn asking_an_exited_group_to_stop_keeps_its_status() {
348 let mut process = spawn("exit 3");
349 let leader = process.group_pid().expect("the pid should be valid");
350 waitid(
351 WaitId::Pid(leader),
352 WaitIdOptions::EXITED | WaitIdOptions::NOWAIT,
353 )
354 .expect("the shell should exit");
355
356 process
357 .request_termination()
358 .expect("a group of exited processes counts as asked");
359
360 let outcome = process
361 .wait_until(Instant::now() + PATIENCE, || false)
362 .expect("waiting should succeed");
363 let WaitOutcome::Exited(status) = outcome else {
364 panic!("the shell should have exited");
365 };
366 assert_eq!(status.code(), Some(3));
367 }
368
369 #[cfg(target_os = "macos")]
370 #[test]
371 fn waiting_reports_the_exit_status() {
372 let mut process = spawn("exit 3");
373
374 let outcome = process
375 .wait_until(Instant::now() + PATIENCE, || false)
376 .expect("waiting should succeed");
377
378 let WaitOutcome::Exited(status) = outcome else {
379 panic!("the shell should have exited");
380 };
381 assert_eq!(status.code(), Some(3));
382 }
383
384 #[cfg(target_os = "macos")]
385 #[test]
386 fn waiting_gives_up_at_the_deadline() {
387 let mut process = spawn("sleep 300");
388
389 let outcome = process
390 .wait_until(Instant::now() + Duration::from_millis(50), || false)
391 .expect("waiting should succeed");
392
393 assert!(matches!(outcome, WaitOutcome::TimedOut));
394 }
395
396 #[cfg(target_os = "macos")]
397 #[test]
398 fn waiting_stops_when_the_caller_cancels() {
399 let mut process = spawn("sleep 300");
400
401 let outcome = process
402 .wait_until(Instant::now() + PATIENCE, || true)
403 .expect("waiting should succeed");
404
405 assert!(matches!(outcome, WaitOutcome::Cancelled));
406 }
407}