use std::{
ffi::{OsStr, OsString},
io,
path::{Path, PathBuf},
process::Stdio,
time::Duration,
};
use tokio::{process::Command, time::sleep};
#[cfg(unix)]
mod unix;
#[cfg(windows)]
mod windows;
#[cfg(unix)]
use unix as native;
#[cfg(unix)]
pub use unix::*;
#[cfg(windows)]
use windows as native;
#[cfg(windows)]
pub use windows::*;
pub async fn spawn_verified(launch: super::executable::Launch<'_>) -> io::Result<Child> {
launch.spawn().await
}
pub struct ResolvedCommand {
command: Command,
binding: self::native::Binding,
}
impl ResolvedCommand {
pub fn as_std(&self) -> &std::process::Command {
self.command.as_std()
}
pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Self {
self.command.current_dir(dir);
self
}
pub fn env_clear(&mut self) -> &mut Self {
self.command.env_clear();
self
}
pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
self.command.env(key, value);
self
}
pub fn envs<K, V>(&mut self, vars: impl IntoIterator<Item = (K, V)>) -> &mut Self
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.command.envs(vars);
self
}
pub fn stdin(&mut self, config: impl Into<Stdio>) -> &mut Self {
self.command.stdin(config);
self
}
pub fn stdout(&mut self, config: impl Into<Stdio>) -> &mut Self {
self.command.stdout(config);
self
}
pub fn stderr(&mut self, config: impl Into<Stdio>) -> &mut Self {
self.command.stderr(config);
self
}
pub fn kill_on_drop(&mut self, enabled: bool) -> &mut Self {
self.command.kill_on_drop(enabled);
self
}
pub fn hide_console_window(&mut self) -> &mut Self {
hide_console_window(self.command.as_std_mut());
self
}
}
pub struct Program {
path: PathBuf,
canonical: PathBuf,
}
impl Program {
fn resolve(path: PathBuf) -> io::Result<Self> {
if !path.is_absolute() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"launch requires a resolved absolute program",
));
}
let canonical = std::fs::canonicalize(&path)?;
Ok(Self { path, canonical })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn canonical_path(&self) -> &Path {
&self.canonical
}
}
pub fn resolve_with(
program: &Path,
cwd: &Path,
variable: impl Fn(&str) -> Option<OsString>,
) -> io::Result<Program> {
Program::resolve(super::program::resolve_with(program, cwd, variable)?)
}
pub fn resolved_command(
program: &Path,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> io::Result<ResolvedCommand> {
Program::resolve(program.to_owned())?.command(args)
}
mod outcome;
pub use outcome::{ProcessEnd, ProcessOutcome};
const CLEANUP_GRACE: Duration = Duration::from_secs(1);
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(transparent)]
pub struct ProcessId(std::num::NonZeroU32);
impl ProcessId {
pub fn new(pid: u32) -> Self {
Self(std::num::NonZeroU32::new(pid).expect("a real process id is never 0"))
}
pub fn get(self) -> u32 {
self.0.get()
}
}
impl From<std::num::NonZeroU32> for ProcessId {
fn from(pid: std::num::NonZeroU32) -> Self {
Self(pid)
}
}
impl std::fmt::Display for ProcessId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ChildIdentity {
pub pid: ProcessId,
pub start_time: u64,
}
pub fn child_identity(pid: u32) -> io::Result<ChildIdentity> {
let start_time = process_start_time(pid)?;
Ok(ChildIdentity {
pid: ProcessId::new(pid),
start_time,
})
}
pub fn is_alive(owner: Option<ChildIdentity>) -> io::Result<bool> {
let Some(owner) = owner else {
return Ok(false);
};
match running_process_start_time(owner.pid.get()) {
Ok(start_time) => Ok(start_time == owner.start_time),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
pub async fn terminate(child: &mut Child) -> io::Result<()> {
let _ = child.interrupt();
tokio::select! {
_ = sleep(CLEANUP_GRACE) => {},
_ = child.wait() => {},
}
child.cleanup().await?;
Ok(())
}
#[cfg(test)]
mod tests;