Skip to main content

crumbkit_process/
group.rs

1//! A started child together with every process that it starts, which the
2//! crate stops and reaps as one.
3
4use std::io;
5use std::process::{ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus};
6
7use crate::sys;
8
9#[cfg(test)]
10mod tests;
11
12/// Which processes a run holds and signals.
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum Scope {
16    /// The child and every process that it starts. On Unix the child leads
17    /// a new process group, and each signal goes to the group. On Windows
18    /// the child runs in a new job object, and a stop ends the job. The job
19    /// object replaces the command's creation flags with its own, which
20    /// start the child suspended, so flags that the caller set with
21    /// `CommandExt::creation_flags` are lost.
22    #[default]
23    Group,
24    /// The child alone. The child stays in the caller's process group, so a
25    /// signal that the caller's terminal sends reaches it too, and each
26    /// signal from the crate goes to the child only. A process that the
27    /// child starts is never stopped by the crate.
28    Child,
29}
30
31/// A signal that a run sends to the processes in its scope.
32///
33/// On Windows every signal ends the child at once: with [`Scope::Group`]
34/// it ends the job and every process in it, and with [`Scope::Child`] it
35/// ends the child alone. Windows has no graceful step that crumbkit can
36/// send without unsafe code (ADR-0171).
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum Signal {
40    /// SIGINT, which Ctrl-C sends.
41    Interrupt,
42    /// SIGTERM, the polite request to end.
43    Terminate,
44    /// SIGHUP, which a closed terminal sends.
45    Hangup,
46    /// SIGKILL, which no process can catch or ignore.
47    Kill,
48}
49
50/// A started child and the processes that it starts, as its [`Scope`]
51/// names them.
52///
53/// On Unix the child stays unreaped until [`Group::reap`], so its process
54/// id cannot pass to another process while a signal could still name it.
55/// [`Group::reap`] waits for the child without reaping it, kills what is
56/// left of the group, reaps the child, and waits until the group is empty
57/// for at most [`REAP_GRACE`](crate::REAP_GRACE). A process that left
58/// the group, such as one that called `setsid`, is not stopped.
59///
60/// A group that is dropped before [`Group::reap`] kills the child and every
61/// process in its scope and reaps the child, so a normal return and a
62/// panic that unwinds leave nothing running. On Windows the drop ends the
63/// job. A tool that is killed outright or crashes skips the drop: on Unix
64/// the group keeps running, and on Windows the job's processes keep
65/// running, because process-wrap's std job object does not ask Windows to
66/// end them when the job's last handle closes.
67#[derive(Debug)]
68pub(crate) struct Group {
69    child: sys::Child,
70    status: Option<ExitStatus>,
71}
72
73impl Group {
74    /// Starts `command` in the scope that `scope` names. The caller sets
75    /// the command's program, arguments, environment and standard streams.
76    ///
77    /// # Errors
78    ///
79    /// Returns the error of [`Command::spawn`] when the program does not
80    /// exist or cannot be started, and on Windows when the job object
81    /// cannot be created.
82    pub(crate) fn start(command: Command, scope: Scope) -> io::Result<Self> {
83        Ok(Self {
84            child: sys::Child::spawn(command, scope)?,
85            status: None,
86        })
87    }
88
89    /// Returns true when another process in the group still runs. The
90    /// child must have exited and stayed unreaped, so it names the group.
91    pub(crate) fn others_alive(&self) -> bool {
92        self.child.others_alive()
93    }
94
95    /// Returns the child's process id.
96    pub(crate) fn id(&self) -> u32 {
97        self.child.id()
98    }
99
100    /// Takes the child's standard input, when the command made it a pipe
101    /// and nobody has taken it yet.
102    pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
103        self.child.take_stdin()
104    }
105
106    /// Takes the child's standard output, when the command made it a pipe
107    /// and nobody has taken it yet.
108    pub(crate) fn take_stdout(&mut self) -> Option<ChildStdout> {
109        self.child.take_stdout()
110    }
111
112    /// Takes the child's standard error, when the command made it a pipe
113    /// and nobody has taken it yet.
114    pub(crate) fn take_stderr(&mut self) -> Option<ChildStderr> {
115        self.child.take_stderr()
116    }
117
118    /// Sends `signal` to the processes in the group's scope. On Unix with
119    /// [`Scope::Group`], a child that moved to another process group gets
120    /// the signal too. A signal that finds every process already gone
121    /// succeeds.
122    ///
123    /// # Errors
124    ///
125    /// Returns an error when the group has been reaped, and the operating
126    /// system's error when it refuses the signal.
127    pub(crate) fn signal(&self, signal: Signal) -> io::Result<()> {
128        if self.status.is_some() {
129            return Err(io::Error::other("the child has been reaped"));
130        }
131        self.child.signal(signal)
132    }
133
134    /// Returns true when the child has exited. The child stays unreaped.
135    ///
136    /// # Errors
137    ///
138    /// Returns the operating system's error when it cannot tell.
139    pub(crate) fn has_exited(&self) -> io::Result<bool> {
140        if self.status.is_some() {
141            return Ok(true);
142        }
143        self.child.has_exited()
144    }
145
146    /// Blocks until the child exits, and leaves it unreaped. It waits as
147    /// long as the child runs.
148    ///
149    /// # Errors
150    ///
151    /// Returns the operating system's error when the wait fails.
152    #[cfg(all(test, unix))]
153    pub(crate) fn wait_exit(&self) -> io::Result<()> {
154        if self.status.is_some() {
155            return Ok(());
156        }
157        self.child.waiter().wait()
158    }
159
160    /// Returns a waiter that a thread of the crate's own blocks on.
161    pub(crate) fn waiter(&self) -> sys::Waiter {
162        self.child.waiter()
163    }
164
165    /// Waits until the child exits, kills what is left in the group's
166    /// scope, reaps the child and returns its exit status. On Unix it then
167    /// waits until the group is empty for at most
168    /// [`REAP_GRACE`](crate::REAP_GRACE) after the exit. A second call
169    /// returns the same status. It waits as long as the child runs, so a
170    /// caller that wants the child gone first sends [`Signal::Kill`].
171    ///
172    /// # Errors
173    ///
174    /// Returns the operating system's error when the wait, the kill or the
175    /// reap fails.
176    pub(crate) fn reap(&mut self) -> io::Result<ExitStatus> {
177        if let Some(status) = self.status {
178            return Ok(status);
179        }
180        let status = self.child.reap()?;
181        self.status = Some(status);
182        Ok(status)
183    }
184}
185
186impl Drop for Group {
187    /// Kills every process in the group's scope and reaps the child, unless
188    /// [`Group::reap`] already reaped it. On Unix the drop can therefore
189    /// block for [`REAP_GRACE`](crate::REAP_GRACE).
190    fn drop(&mut self) {
191        if self.status.is_none() {
192            let _ = self.child.signal(Signal::Kill);
193            let _ = self.reap();
194        }
195    }
196}