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 if self.child.is_none() {
118 return Ok(self.exit_status);
119 }
120 if !self.child_exited()? {
121 return Ok(None);
122 }
123 self.terminate_group()?;
126 let status = self
127 .child_mut()?
128 .try_wait()
129 .map_err(ChildProcessError::Inspect)?;
130 if status.is_some() {
131 self.child = None;
132 self.exit_status = status;
133 }
134 Ok(status)
135 }
136
137 fn reap(&mut self) -> Result<(), ChildProcessError> {
138 let status = self.child_mut()?.wait().map_err(ChildProcessError::Reap)?;
139 self.child = None;
140 self.exit_status = Some(status);
141 Ok(())
142 }
143
144 pub fn request_termination(&self) -> Result<(), ChildProcessError> {
148 if !self.owns_process_group {
149 return Ok(());
150 }
151 self.signal_group(Signal::TERM)
152 }
153
154 fn terminate_group(&mut self) -> Result<(), ChildProcessError> {
155 if !self.owns_process_group {
156 return Ok(());
157 }
158
159 self.signal_group(Signal::KILL)?;
160 self.owns_process_group = false;
161 Ok(())
162 }
163
164 fn signal_group(&self, signal: Signal) -> Result<(), ChildProcessError> {
166 match kill_process_group(self.group_pid()?, signal) {
167 Ok(()) | Err(Errno::SRCH) => Ok(()),
168 #[cfg(target_os = "macos")]
172 Err(Errno::PERM) if self.child_exited()? => Ok(()),
173 Err(source) => Err(ChildProcessError::TerminateGroup(source.into())),
174 }
175 }
176
177 fn child_exited(&self) -> Result<bool, ChildProcessError> {
180 use rustix::process::{WaitId, WaitIdOptions, waitid};
181
182 let Some(child) = &self.child else {
183 return Ok(true);
184 };
185 let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT;
186 waitid(WaitId::Pid(Pid::from_child(child)), options)
187 .map(|status| status.is_some())
188 .map_err(|source| ChildProcessError::Inspect(source.into()))
189 }
190
191 fn group_pid(&self) -> Result<Pid, ChildProcessError> {
192 let raw_pid = i32::try_from(self.process_group)
193 .map_err(|_error| io::Error::other("child process identifier is out of range"))
194 .map_err(ChildProcessError::TerminateGroup)?;
195 Pid::from_raw(raw_pid)
196 .ok_or_else(|| io::Error::other("child process identifier is invalid"))
197 .map_err(ChildProcessError::TerminateGroup)
198 }
199
200 fn child_mut(&mut self) -> Result<&mut Child, ChildProcessError> {
201 self.child.as_mut().ok_or(ChildProcessError::MissingChild)
202 }
203}
204
205impl Drop for ChildProcess {
206 fn drop(&mut self) {
207 if (self.child.is_some() || self.owns_process_group)
208 && let Err(error) = self.terminate_inner()
209 {
210 tracing::error!(?error, "failed to clean up child process before drop");
211 }
212 }
213}
214
215pub enum WaitOutcome {
216 Exited(ExitStatus),
217 Cancelled,
218 TimedOut,
219}
220
221#[derive(Debug, thiserror::Error)]
222pub enum ChildProcessError {
223 #[error("child process ownership ended before cleanup completed")]
224 MissingChild,
225
226 #[error("failed to inspect the child process")]
227 Inspect(#[source] io::Error),
228
229 #[error("failed to terminate the child process group")]
230 TerminateGroup(#[source] io::Error),
231
232 #[error("failed to terminate the child process")]
233 TerminateProcess(#[source] io::Error),
234
235 #[error("failed to reap the child process")]
236 Reap(#[source] io::Error),
237}
238
239#[cfg(test)]
240mod tests {
241 use std::io::{BufRead, BufReader};
242 use std::process::Stdio;
243 use std::thread;
244 use std::time::{Duration, Instant};
245
246 use rustix::process::{WaitId, WaitIdOptions, test_kill_process, waitid};
247
248 use super::super::POLL_INTERVAL;
249 use super::*;
250
251 const PATIENCE: Duration = Duration::from_secs(5);
252
253 fn shell(script: &str) -> Command {
254 let mut command = Command::new("/bin/sh");
255 command.arg("-c").arg(script);
256 command
257 }
258
259 fn spawn(script: &str) -> ChildProcess {
260 ChildProcess::spawn(&mut shell(script)).expect("the shell should start")
261 }
262
263 fn spawn_group() -> (ChildProcess, Pid) {
266 let mut command = shell("sleep 300 & echo $!");
267 command.stdout(Stdio::piped());
268 let mut process = ChildProcess::spawn(&mut command).expect("the shell should start");
269
270 let stdout = process.take_stdout().expect("stdout should be piped");
271 let mut line = String::new();
272 BufReader::new(stdout)
273 .read_line(&mut line)
274 .expect("the shell should report its child");
275 let raw = line.trim().parse().expect("the report should be a pid");
276
277 (
278 process,
279 Pid::from_raw(raw).expect("the pid should be valid"),
280 )
281 }
282
283 fn eventually(mut condition: impl FnMut() -> bool) -> bool {
286 let deadline = Instant::now() + PATIENCE;
287 while Instant::now() < deadline {
288 if condition() {
289 return true;
290 }
291 thread::sleep(POLL_INTERVAL);
292 }
293 false
294 }
295
296 fn gone(pid: Pid) -> bool {
297 eventually(|| test_kill_process(pid).is_err())
298 }
299
300 fn exited(process: &mut ChildProcess) -> bool {
301 eventually(|| {
302 process
303 .try_wait()
304 .expect("inspection should succeed")
305 .is_some()
306 })
307 }
308
309 #[test]
310 fn dropping_a_process_kills_its_whole_group() {
311 let (process, grandchild) = spawn_group();
312
313 drop(process);
314
315 assert!(gone(grandchild), "the grandchild outlived its group");
316 }
317
318 #[test]
319 fn seeing_the_leader_exit_kills_the_rest_of_its_group() {
320 let (mut process, grandchild) = spawn_group();
321
322 assert!(exited(&mut process), "the shell should exit on its own");
323
324 assert!(
325 gone(grandchild),
326 "the grandchild outlived its reaped leader"
327 );
328 }
329
330 #[test]
331 fn terminating_kills_the_whole_group() {
332 let (mut process, grandchild) = spawn_group();
333
334 process
335 .terminate_in_place()
336 .expect("cleanup should succeed");
337
338 assert!(gone(grandchild), "the grandchild outlived its group");
339 }
340
341 #[test]
342 fn cleanup_succeeds_once_the_child_has_exited() {
343 let mut process = spawn("exit 0");
344 assert!(exited(&mut process), "the shell should exit on its own");
345
346 process
347 .terminate_in_place()
348 .expect("cleanup should succeed");
349 }
350
351 #[test]
352 fn cleanup_succeeds_when_the_child_died_after_the_last_check() {
353 let mut process = spawn("exit 0");
354 let leader = process.group_pid().expect("the pid should be valid");
355 waitid(
356 WaitId::Pid(leader),
357 WaitIdOptions::EXITED | WaitIdOptions::NOWAIT,
358 )
359 .expect("the shell should exit");
360
361 process
362 .terminate_group()
363 .expect("a group of exited processes is already gone");
364 }
365
366 #[test]
367 fn asking_an_exited_group_to_stop_keeps_its_status() {
368 let mut process = spawn("exit 3");
369 let leader = process.group_pid().expect("the pid should be valid");
370 waitid(
371 WaitId::Pid(leader),
372 WaitIdOptions::EXITED | WaitIdOptions::NOWAIT,
373 )
374 .expect("the shell should exit");
375
376 process
377 .request_termination()
378 .expect("a group of exited processes counts as asked");
379
380 let outcome = process
381 .wait_until(Instant::now() + PATIENCE, || false)
382 .expect("waiting should succeed");
383 let WaitOutcome::Exited(status) = outcome else {
384 panic!("the shell should have exited");
385 };
386 assert_eq!(status.code(), Some(3));
387 }
388
389 #[cfg(target_os = "macos")]
390 #[test]
391 fn waiting_reports_the_exit_status() {
392 let mut process = spawn("exit 3");
393
394 let outcome = process
395 .wait_until(Instant::now() + PATIENCE, || false)
396 .expect("waiting should succeed");
397
398 let WaitOutcome::Exited(status) = outcome else {
399 panic!("the shell should have exited");
400 };
401 assert_eq!(status.code(), Some(3));
402 }
403
404 #[cfg(target_os = "macos")]
405 #[test]
406 fn waiting_gives_up_at_the_deadline() {
407 let mut process = spawn("sleep 300");
408
409 let outcome = process
410 .wait_until(Instant::now() + Duration::from_millis(50), || false)
411 .expect("waiting should succeed");
412
413 assert!(matches!(outcome, WaitOutcome::TimedOut));
414 }
415
416 #[cfg(target_os = "macos")]
417 #[test]
418 fn waiting_stops_when_the_caller_cancels() {
419 let mut process = spawn("sleep 300");
420
421 let outcome = process
422 .wait_until(Instant::now() + PATIENCE, || true)
423 .expect("waiting should succeed");
424
425 assert!(matches!(outcome, WaitOutcome::Cancelled));
426 }
427}