use std::{io, process::ExitStatus, time::Duration};
use tokio::process::{ChildStderr, ChildStdout, Command};
pub struct Child {
inner: imp::Child,
}
impl Child {
pub fn spawn(command: &mut Command) -> io::Result<Self> {
imp::Child::spawn(command).map(|inner| Self { inner })
}
pub fn id(&self) -> Option<u32> {
self.inner.id()
}
pub fn stdout(&mut self) -> Option<ChildStdout> {
self.inner.child().stdout.take()
}
pub fn stderr(&mut self) -> Option<ChildStderr> {
self.inner.child().stderr.take()
}
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
self.inner.child().try_wait()
}
pub fn kill(&mut self) {
self.inner.kill();
}
pub async fn stop(&mut self) {
self.inner.terminate().await;
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
let exited = self.try_wait().ok().flatten().is_some();
if exited && !self.inner.alive() {
break;
}
if tokio::time::Instant::now() >= deadline {
break;
}
tokio::time::sleep(Duration::from_millis(30)).await;
}
self.inner.kill();
let _ = self.inner.wait().await;
}
}
impl Drop for Child {
fn drop(&mut self) {
self.inner.kill();
}
}
#[cfg(all(test, windows))]
mod tests {
use super::*;
use tokio::io::{AsyncBufReadExt, BufReader};
#[tokio::test]
async fn windows_job_shutdown_closes_descendant_listener() {
let script = r#"
const { spawn } = require('node:child_process');
const child = spawn(process.execPath, ['-e',
"require('node:net').createServer(s => s.end()).listen(0, '127.0.0.1', function() { console.log(JSON.stringify({ port: this.address().port, pid: process.pid })) })"
], { stdio: ['ignore', 'pipe', 'ignore'] });
child.stdout.pipe(process.stdout);
setInterval(() => {}, 1000);
"#;
let mut command = Command::new("node");
command
.args(["-e", script])
.stdout(std::process::Stdio::piped());
let mut child = Child::spawn(&mut command).expect("Windows CI must install Node");
let mut stdout = BufReader::new(child.stdout().unwrap());
let mut line = String::new();
tokio::time::timeout(Duration::from_secs(10), stdout.read_line(&mut line))
.await
.unwrap()
.unwrap();
let info: serde_json::Value = serde_json::from_str(line.trim()).unwrap();
let port = info["port"].as_u64().unwrap() as u16;
let pid = info["pid"].as_u64().unwrap();
assert!(std::net::TcpStream::connect(("127.0.0.1", port)).is_ok());
tokio::time::timeout(Duration::from_secs(8), child.stop())
.await
.unwrap();
let probe = format!(
"try {{ process.kill({pid}, 0); process.exit(1) }} catch (e) {{ process.exit(e.code === 'ESRCH' ? 0 : 2) }}"
);
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let status = Command::new("node")
.args(["-e", &probe])
.status()
.await
.unwrap();
assert_ne!(status.code(), Some(2), "Could not inspect descendant {pid}");
if status.success() {
break;
}
tokio::time::sleep(Duration::from_millis(30)).await;
}
})
.await
.expect("Job shutdown left a descendant process alive");
assert!(
std::net::TcpStream::connect_timeout(
&std::net::SocketAddr::from(([127, 0, 0, 1], port)),
Duration::from_secs(1),
)
.is_err(),
"Job shutdown left a descendant listening"
);
}
}
#[cfg(unix)]
mod imp {
use super::*;
use nix::{
sys::signal::{killpg, Signal},
unistd::Pid,
};
pub struct Child {
child: tokio::process::Child,
group: Pid,
armed: bool,
}
impl Child {
pub fn spawn(command: &mut Command) -> io::Result<Self> {
let child = command.process_group(0).kill_on_drop(true).spawn()?;
let group = Pid::from_raw(child.id().expect("new child has a PID") as i32);
Ok(Self {
child,
group,
armed: true,
})
}
pub fn child(&mut self) -> &mut tokio::process::Child {
&mut self.child
}
pub fn id(&self) -> Option<u32> {
self.child.id()
}
pub async fn wait(&mut self) -> io::Result<ExitStatus> {
self.child.wait().await
}
pub async fn terminate(&mut self) {
if self.armed {
let _ = killpg(self.group, Signal::SIGTERM);
}
}
pub fn alive(&self) -> bool {
self.armed && killpg(self.group, None).is_ok()
}
pub fn kill(&mut self) {
if self.armed {
let _ = killpg(self.group, Signal::SIGKILL);
self.armed = false;
}
}
}
}
#[cfg(windows)]
mod imp {
use super::*;
use command_group::{AsyncCommandGroup, AsyncGroupChild};
pub struct Child {
group: AsyncGroupChild,
}
impl Child {
pub fn spawn(command: &mut Command) -> io::Result<Self> {
command
.kill_on_drop(true)
.group()
.kill_on_drop(true)
.spawn()
.map(|group| Self { group })
}
pub fn child(&mut self) -> &mut tokio::process::Child {
self.group.inner()
}
pub fn id(&self) -> Option<u32> {
self.group.id()
}
pub async fn wait(&mut self) -> io::Result<ExitStatus> {
self.group.wait().await
}
pub async fn terminate(&mut self) {
if let Some(pid) = self.id() {
let _ = tokio::time::timeout(
Duration::from_secs(1),
Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/T"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.kill_on_drop(true)
.status(),
)
.await;
}
}
pub fn alive(&self) -> bool {
self.group.id().is_some()
}
pub fn kill(&mut self) {
if let Err(error) = self.group.start_kill() {
eprintln!("Could not terminate child process job: {error}");
}
}
}
}
pub struct Signals {
#[cfg(unix)]
interrupt: tokio::signal::unix::Signal,
#[cfg(unix)]
terminate: tokio::signal::unix::Signal,
#[cfg(unix)]
hangup: tokio::signal::unix::Signal,
#[cfg(windows)]
interrupt: tokio::signal::windows::CtrlC,
#[cfg(windows)]
close: tokio::signal::windows::CtrlClose,
#[cfg(windows)]
shutdown: tokio::signal::windows::CtrlShutdown,
#[cfg(windows)]
logoff: tokio::signal::windows::CtrlLogoff,
#[cfg(windows)]
ctrl_break: tokio::signal::windows::CtrlBreak,
}
impl Signals {
pub fn new() -> io::Result<Self> {
#[cfg(unix)]
{
use tokio::signal::unix::{signal, SignalKind};
Ok(Self {
interrupt: signal(SignalKind::interrupt())?,
terminate: signal(SignalKind::terminate())?,
hangup: signal(SignalKind::hangup())?,
})
}
#[cfg(windows)]
{
use tokio::signal::windows::*;
Ok(Self {
interrupt: ctrl_c()?,
close: ctrl_close()?,
shutdown: ctrl_shutdown()?,
logoff: ctrl_logoff()?,
ctrl_break: ctrl_break()?,
})
}
}
pub async fn recv(&mut self) {
#[cfg(unix)]
tokio::select! { _ = self.interrupt.recv() => {}, _ = self.terminate.recv() => {}, _ = self.hangup.recv() => {} }
#[cfg(windows)]
tokio::select! { _ = self.interrupt.recv() => {}, _ = self.close.recv() => {}, _ = self.shutdown.recv() => {}, _ = self.logoff.recv() => {}, _ = self.ctrl_break.recv() => {} }
}
}