refactor(sidecar): enable kill on drop for the managed child

This commit is contained in:
Tunglies
2026-12-04 15:36:19 +08:00
parent 06329c3337
commit 287752daff
+60 -1
View File
@@ -227,7 +227,7 @@ impl CoreManager {
.shell()
.sidecar(clash_core.as_str())
.map_err(|error| anyhow::anyhow!("failed to build sidecar command for core {clash_core:?}: {error:#}"))?;
let command = command.args([
let command = command.kill_on_drop(true).args([
"-d",
dirs::path_to_str(&config_dir)?,
"-f",
@@ -730,6 +730,65 @@ mod tests {
Ok(())
}
#[test]
fn forced_parent_exit_releases_the_sidecar_job() -> Result<()> {
use std::io::{BufRead as _, BufReader, Write as _};
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
use windows_sys::Win32::{
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},
};
const HELPER: &str = "CVR_TEST_SIDECAR_JOB_PARENT";
if std::env::var_os(HELPER).is_some() {
let mut child = spawn_long_lived()?;
let _job = create_and_assign_sidecar_job(child.id()).inspect_err(|_| {
let _ = child.kill();
let _ = child.wait();
})?;
println!("\nSIDECAR_PID={}", child.id());
std::io::stdout().flush()?;
std::io::stdin().read_line(&mut String::new())?;
return Ok(());
}
let mut parent = std::mem::DropGuard::new(
Command::new(std::env::current_exe()?)
.args(["forced_parent_exit_releases_the_sidecar_job", "--nocapture"])
.env(HELPER, "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?,
|mut parent| {
let _ = parent.kill();
let _ = parent.wait();
},
);
let stdout = parent
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("missing helper stdout"))?;
let mut pid = None;
for line in BufReader::new(stdout).lines() {
if let Some(value) = line?.strip_prefix("SIDECAR_PID=") {
pid = Some(value.parse()?);
break;
}
}
let pid = pid.ok_or_else(|| anyhow::anyhow!("helper did not report its child"))?;
let raw = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
anyhow::ensure!(!raw.is_null(), "could not open helper child {pid}");
let child = unsafe { OwnedHandle::from_raw_handle(raw) };
assert_eq!(unsafe { WaitForSingleObject(child.as_raw_handle(), 0) }, WAIT_TIMEOUT);
parent.kill()?;
parent.wait()?;
assert_eq!(
unsafe { WaitForSingleObject(child.as_raw_handle(), 5000) },
WAIT_OBJECT_0
);
Ok(())
}
#[test]
fn returns_err_for_invalid_pid() {
// Windows PIDs are multiples of four; this one is effectively impossible.