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    #[cfg(all(test, unix))]
97    pub(crate) fn id(&self) -> u32 {
98        self.child.id()
99    }
100
101    /// Takes the child's standard input, when the command made it a pipe
102    /// and nobody has taken it yet.
103    pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
104        self.child.take_stdin()
105    }
106
107    /// Takes the child's standard output, when the command made it a pipe
108    /// and nobody has taken it yet.
109    pub(crate) fn take_stdout(&mut self) -> Option<ChildStdout> {
110        self.child.take_stdout()
111    }
112
113    /// Takes the child's standard error, when the command made it a pipe
114    /// and nobody has taken it yet.
115    pub(crate) fn take_stderr(&mut self) -> Option<ChildStderr> {
116        self.child.take_stderr()
117    }
118
119    /// Sends `signal` to the processes in the group's scope. On Unix with
120    /// [`Scope::Group`], a child that moved to another process group gets
121    /// the signal too. A signal that finds every process already gone
122    /// succeeds.
123    ///
124    /// # Errors
125    ///
126    /// Returns an error when the group has been reaped, and the operating
127    /// system's error when it refuses the signal.
128    pub(crate) fn signal(&self, signal: Signal) -> io::Result<()> {
129        if self.status.is_some() {
130            return Err(io::Error::other("the child has been reaped"));
131        }
132        self.child.signal(signal)
133    }
134
135    /// Returns true when the child has exited. The child stays unreaped.
136    ///
137    /// # Errors
138    ///
139    /// Returns the operating system's error when it cannot tell.
140    pub(crate) fn has_exited(&self) -> io::Result<bool> {
141        if self.status.is_some() {
142            return Ok(true);
143        }
144        self.child.has_exited()
145    }
146
147    /// Blocks until the child exits, and leaves it unreaped. It waits as
148    /// long as the child runs.
149    ///
150    /// # Errors
151    ///
152    /// Returns the operating system's error when the wait fails.
153    #[cfg(all(test, unix))]
154    pub(crate) fn wait_exit(&self) -> io::Result<()> {
155        if self.status.is_some() {
156            return Ok(());
157        }
158        self.child.waiter().wait()
159    }
160
161    /// Returns a waiter that a thread of the crate's own blocks on.
162    pub(crate) fn waiter(&self) -> sys::Waiter {
163        self.child.waiter()
164    }
165
166    /// Waits until the child exits, kills what is left in the group's
167    /// scope, reaps the child and returns its exit status. On Unix it then
168    /// waits until the group is empty for at most
169    /// [`REAP_GRACE`](crate::REAP_GRACE) after the exit. A second call
170    /// returns the same status. It waits as long as the child runs, so a
171    /// caller that wants the child gone first sends [`Signal::Kill`].
172    ///
173    /// # Errors
174    ///
175    /// Returns the operating system's error when the wait, the kill or the
176    /// reap fails.
177    pub(crate) fn reap(&mut self) -> io::Result<ExitStatus> {
178        if let Some(status) = self.status {
179            return Ok(status);
180        }
181        let status = self.child.reap()?;
182        self.status = Some(status);
183        Ok(status)
184    }
185}
186
187impl Drop for Group {
188    /// Kills every process in the group's scope and reaps the child, unless
189    /// [`Group::reap`] already reaped it. On Unix the drop can therefore
190    /// block for [`REAP_GRACE`](crate::REAP_GRACE).
191    fn drop(&mut self) {
192        if self.status.is_none() {
193            let _ = self.child.signal(Signal::Kill);
194            let _ = self.reap();
195        }
196    }
197}