use std::io;
use std::process::{ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus};
use crate::sys;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Scope {
#[default]
Group,
Child,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Signal {
Interrupt,
Terminate,
Hangup,
Kill,
}
#[derive(Debug)]
pub(crate) struct Group {
child: sys::Child,
state: State,
}
#[derive(Clone, Copy, Debug)]
enum State {
Unreaped,
Reaped(ExitStatus),
Gone,
}
impl Group {
pub(crate) fn start(command: Command, scope: Scope) -> io::Result<Self> {
Ok(Self {
child: sys::Child::spawn(command, scope)?,
state: State::Unreaped,
})
}
pub(crate) fn others_alive(&self) -> bool {
self.child.others_alive()
}
pub(crate) fn id(&self) -> u32 {
self.child.id()
}
pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
self.child.take_stdin()
}
pub(crate) fn take_stdout(&mut self) -> Option<ChildStdout> {
self.child.take_stdout()
}
pub(crate) fn take_stderr(&mut self) -> Option<ChildStderr> {
self.child.take_stderr()
}
pub(crate) fn signal(&self, signal: Signal) -> io::Result<()> {
match self.state {
State::Unreaped => self.child.signal(signal),
State::Reaped(_) => Err(io::Error::other("the child has been reaped")),
State::Gone => Err(io::Error::other("the child is gone")),
}
}
pub(crate) fn has_exited(&self) -> io::Result<bool> {
if !matches!(self.state, State::Unreaped) {
return Ok(true);
}
self.child.has_exited()
}
#[cfg(all(test, unix))]
pub(crate) fn wait_exit(&self) -> io::Result<()> {
if !matches!(self.state, State::Unreaped) {
return Ok(());
}
self.child.waiter().wait()
}
pub(crate) fn waiter(&self) -> sys::Waiter {
self.child.waiter()
}
pub(crate) fn reap(&mut self) -> io::Result<ExitStatus> {
match self.state {
State::Reaped(status) => return Ok(status),
State::Gone => {
return Err(io::Error::new(io::ErrorKind::NotFound, "the child is gone"));
}
State::Unreaped => {}
}
match self.child.reap() {
Ok(status) => {
self.state = State::Reaped(status);
Ok(status)
}
Err(error) => {
if sys::Child::is_gone(&error) {
self.state = State::Gone;
}
Err(error)
}
}
}
}
impl Drop for Group {
fn drop(&mut self) {
if matches!(self.state, State::Unreaped) {
let _ = self.child.signal(Signal::Kill);
let _ = self.reap();
}
}
}