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, and only then reaps the child. A process that left
57/// the group, such as one that called `setsid`, is not stopped.
58///
59/// A group that is dropped before [`Group::reap`] kills the child and every
60/// process in its scope and reaps the child, so a normal return and a
61/// panic that unwinds leave nothing running. On Windows the drop ends the
62/// job. A tool that is killed outright or crashes skips the drop: on Unix
63/// the group keeps running, and on Windows the job's processes keep
64/// running, because process-wrap's std job object does not ask Windows to
65/// end them when the job's last handle closes.
66#[derive(Debug)]
67pub(crate) struct Group {
68 child: sys::Child,
69 status: Option<ExitStatus>,
70}
71
72impl Group {
73 /// Starts `command` in the scope that `scope` names. The caller sets
74 /// the command's program, arguments, environment and standard streams.
75 ///
76 /// # Errors
77 ///
78 /// Returns the error of [`Command::spawn`] when the program does not
79 /// exist or cannot be started, and on Windows when the job object
80 /// cannot be created.
81 pub(crate) fn start(command: Command, scope: Scope) -> io::Result<Self> {
82 Ok(Self {
83 child: sys::Child::spawn(command, scope)?,
84 status: None,
85 })
86 }
87
88 /// Returns the child's process id.
89 #[cfg(all(test, unix))]
90 pub(crate) fn id(&self) -> u32 {
91 self.child.id()
92 }
93
94 /// Takes the child's standard input, when the command made it a pipe
95 /// and nobody has taken it yet.
96 pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
97 self.child.take_stdin()
98 }
99
100 /// Takes the child's standard output, when the command made it a pipe
101 /// and nobody has taken it yet.
102 pub(crate) fn take_stdout(&mut self) -> Option<ChildStdout> {
103 self.child.take_stdout()
104 }
105
106 /// Takes the child's standard error, when the command made it a pipe
107 /// and nobody has taken it yet.
108 pub(crate) fn take_stderr(&mut self) -> Option<ChildStderr> {
109 self.child.take_stderr()
110 }
111
112 /// Sends `signal` to the processes in the group's scope. On Unix with
113 /// [`Scope::Group`], a child that moved to another process group gets
114 /// the signal too. A signal that finds every process already gone
115 /// succeeds.
116 ///
117 /// # Errors
118 ///
119 /// Returns an error when the group has been reaped, and the operating
120 /// system's error when it refuses the signal.
121 pub(crate) fn signal(&self, signal: Signal) -> io::Result<()> {
122 if self.status.is_some() {
123 return Err(io::Error::other("the child has been reaped"));
124 }
125 self.child.signal(signal)
126 }
127
128 /// Returns true when the child has exited. The child stays unreaped.
129 ///
130 /// # Errors
131 ///
132 /// Returns the operating system's error when it cannot tell.
133 pub(crate) fn has_exited(&self) -> io::Result<bool> {
134 if self.status.is_some() {
135 return Ok(true);
136 }
137 self.child.has_exited()
138 }
139
140 /// Blocks until the child exits, and leaves it unreaped. It waits as
141 /// long as the child runs.
142 ///
143 /// # Errors
144 ///
145 /// Returns the operating system's error when the wait fails.
146 #[cfg(all(test, unix))]
147 pub(crate) fn wait_exit(&self) -> io::Result<()> {
148 if self.status.is_some() {
149 return Ok(());
150 }
151 self.child.waiter().wait()
152 }
153
154 /// Returns a waiter that a thread of the crate's own blocks on.
155 pub(crate) fn waiter(&self) -> sys::Waiter {
156 self.child.waiter()
157 }
158
159 /// Waits until the child exits, kills what is left in the group's
160 /// scope, reaps the child and returns its exit status. A second call
161 /// returns the same status. It waits as long as the child runs, so a
162 /// caller that wants the child gone first sends [`Signal::Kill`].
163 ///
164 /// # Errors
165 ///
166 /// Returns the operating system's error when the wait, the kill or the
167 /// reap fails.
168 pub(crate) fn reap(&mut self) -> io::Result<ExitStatus> {
169 if let Some(status) = self.status {
170 return Ok(status);
171 }
172 let status = self.child.reap()?;
173 self.status = Some(status);
174 Ok(status)
175 }
176}
177
178impl Drop for Group {
179 /// Kills every process in the group's scope and reaps the child, unless
180 /// [`Group::reap`] already reaped it.
181 fn drop(&mut self) {
182 if self.status.is_none() {
183 let _ = self.child.signal(Signal::Kill);
184 let _ = self.reap();
185 }
186 }
187}