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    state: State,
71}
72
73/// What a group knows about its child's reap.
74#[derive(Clone, Copy, Debug)]
75enum State {
76    /// This crate has not reaped the child, so its id names the run's group.
77    Unreaped,
78    /// [`Group::reap`] reaped the child and kept its status.
79    Reaped(ExitStatus),
80    /// A wait found that the child is no longer this process's child, so
81    /// something else reaped it and its id may name another group now.
82    Gone,
83}
84
85impl Group {
86    /// Starts `command` in the scope that `scope` names. The caller sets
87    /// the command's program, arguments, environment and standard streams.
88    ///
89    /// # Errors
90    ///
91    /// Returns the error of [`Command::spawn`] when the program does not
92    /// exist or cannot be started, and on Windows when the job object
93    /// cannot be created.
94    pub(crate) fn start(command: Command, scope: Scope) -> io::Result<Self> {
95        Ok(Self {
96            child: sys::Child::spawn(command, scope)?,
97            state: State::Unreaped,
98        })
99    }
100
101    /// Returns true when another process in the group still runs. The
102    /// child must have exited and stayed unreaped, so it names the group.
103    pub(crate) fn others_alive(&self) -> bool {
104        self.child.others_alive()
105    }
106
107    /// Returns the child's process id.
108    pub(crate) fn id(&self) -> u32 {
109        self.child.id()
110    }
111
112    /// Takes the child's standard input, when the command made it a pipe
113    /// and nobody has taken it yet.
114    pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
115        self.child.take_stdin()
116    }
117
118    /// Takes the child's standard output, when the command made it a pipe
119    /// and nobody has taken it yet.
120    pub(crate) fn take_stdout(&mut self) -> Option<ChildStdout> {
121        self.child.take_stdout()
122    }
123
124    /// Takes the child's standard error, when the command made it a pipe
125    /// and nobody has taken it yet.
126    pub(crate) fn take_stderr(&mut self) -> Option<ChildStderr> {
127        self.child.take_stderr()
128    }
129
130    /// Sends `signal` to the processes in the group's scope. On Unix with
131    /// [`Scope::Group`], a child that moved to another process group gets
132    /// the signal too. A signal that finds every process already gone
133    /// succeeds.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error when the group has been reaped or the child is gone,
138    /// and the operating system's error when it refuses the signal.
139    pub(crate) fn signal(&self, signal: Signal) -> io::Result<()> {
140        match self.state {
141            State::Unreaped => self.child.signal(signal),
142            State::Reaped(_) => Err(io::Error::other("the child has been reaped")),
143            State::Gone => Err(io::Error::other("the child is gone")),
144        }
145    }
146
147    /// Returns true when the child has exited. The child stays unreaped.
148    ///
149    /// # Errors
150    ///
151    /// Returns the operating system's error when it cannot tell.
152    pub(crate) fn has_exited(&self) -> io::Result<bool> {
153        if !matches!(self.state, State::Unreaped) {
154            return Ok(true);
155        }
156        self.child.has_exited()
157    }
158
159    /// Blocks until the child exits, and leaves it unreaped. It waits as
160    /// long as the child runs.
161    ///
162    /// # Errors
163    ///
164    /// Returns the operating system's error when the wait fails.
165    #[cfg(all(test, unix))]
166    pub(crate) fn wait_exit(&self) -> io::Result<()> {
167        if !matches!(self.state, State::Unreaped) {
168            return Ok(());
169        }
170        self.child.waiter().wait()
171    }
172
173    /// Returns a waiter that a thread of the crate's own blocks on.
174    pub(crate) fn waiter(&self) -> sys::Waiter {
175        self.child.waiter()
176    }
177
178    /// Waits until the child exits, kills what is left in the group's
179    /// scope, reaps the child and returns its exit status. On Unix it then
180    /// waits until the group is empty for at most
181    /// [`REAP_GRACE`](crate::REAP_GRACE) after the exit. A second call
182    /// returns the same status. After a wait finds that the child is no
183    /// longer this process's child, no later call signals or waits, and a
184    /// second call returns [`io::ErrorKind::NotFound`]. It waits as long
185    /// as the child runs, so a caller that wants the child gone first
186    /// sends [`Signal::Kill`].
187    ///
188    /// # Errors
189    ///
190    /// Returns the operating system's error when the wait, the kill or the
191    /// reap fails.
192    pub(crate) fn reap(&mut self) -> io::Result<ExitStatus> {
193        match self.state {
194            State::Reaped(status) => return Ok(status),
195            State::Gone => {
196                return Err(io::Error::new(io::ErrorKind::NotFound, "the child is gone"));
197            }
198            State::Unreaped => {}
199        }
200        match self.child.reap() {
201            Ok(status) => {
202                self.state = State::Reaped(status);
203                Ok(status)
204            }
205            Err(error) => {
206                if sys::Child::is_gone(&error) {
207                    self.state = State::Gone;
208                }
209                Err(error)
210            }
211        }
212    }
213}
214
215impl Drop for Group {
216    /// Kills every process in the group's scope and reaps the child, unless
217    /// [`Group::reap`] already reaped it or found it gone. On Unix the drop
218    /// can therefore block for [`REAP_GRACE`](crate::REAP_GRACE).
219    fn drop(&mut self) {
220        if matches!(self.state, State::Unreaped) {
221            let _ = self.child.signal(Signal::Kill);
222            let _ = self.reap();
223        }
224    }
225}