use std::io;
use std::process::{ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use process_wrap::std::{ChildWrapper, CommandWrap, JobObject};
use crate::{Scope, Signal, Status};
pub(crate) use std::os::windows::io::AsHandle as Pipe;
pub(crate) const GRACEFUL: bool = false;
const CHECK: Duration = Duration::from_millis(10);
#[derive(Debug)]
pub(crate) struct Child {
wrapped: Arc<Mutex<Box<dyn ChildWrapper>>>,
scope: Scope,
}
impl Child {
pub(crate) fn spawn(command: Command, scope: Scope) -> io::Result<Self> {
let mut wrap = CommandWrap::from(command);
if scope == Scope::Group {
wrap.wrap(JobObject);
}
let child = wrap.spawn()?;
Ok(Self {
wrapped: Arc::new(Mutex::new(child)),
scope,
})
}
pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
locked(&self.wrapped).stdin().take()
}
pub(crate) fn take_stdout(&mut self) -> Option<ChildStdout> {
locked(&self.wrapped).stdout().take()
}
pub(crate) fn take_stderr(&mut self) -> Option<ChildStderr> {
locked(&self.wrapped).stderr().take()
}
pub(crate) fn signal(&self, _signal: Signal) -> io::Result<()> {
locked(&self.wrapped).start_kill()
}
pub(crate) fn has_exited(&self) -> io::Result<bool> {
Ok(locked(&self.wrapped).try_wait()?.is_some())
}
pub(crate) fn waiter(&self) -> Waiter {
Waiter(Arc::clone(&self.wrapped))
}
pub(crate) fn reap(&mut self) -> io::Result<ExitStatus> {
self.waiter().wait()?;
let mut child = locked(&self.wrapped);
if self.scope == Scope::Group {
child.start_kill()?;
}
loop {
if let Some(status) = child.try_wait()? {
return Ok(status);
}
std::thread::sleep(CHECK);
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct Waiter(Arc<Mutex<Box<dyn ChildWrapper>>>);
impl Waiter {
pub(crate) fn wait(self) -> io::Result<()> {
loop {
if locked(&self.0).try_wait()?.is_some() {
return Ok(());
}
std::thread::sleep(CHECK);
}
}
}
fn locked(child: &Mutex<Box<dyn ChildWrapper>>) -> MutexGuard<'_, Box<dyn ChildWrapper>> {
child.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn status_of(status: ExitStatus) -> Status {
Status::Code(status.code().unwrap_or(1))
}
#[expect(
clippy::unnecessary_wraps,
reason = "the Unix function of the same name can fail, and the run calls both alike"
)]
pub(crate) fn ready(_pipe: impl Pipe, _write: bool, _timeout: Duration) -> io::Result<bool> {
Ok(true)
}
#[expect(
clippy::unnecessary_wraps,
reason = "the Unix function of the same name can fail, and the run calls both alike"
)]
pub(crate) fn unblock(_pipe: impl Pipe) -> io::Result<()> {
Ok(())
}