diff --git a/src/exec.rs b/src/exec.rs index 1c4a594..e7b60cf 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -1677,7 +1677,7 @@ impl Shell { } }; if !appends.is_empty() { - crate::io::append_started(&appends, child.id()); + crate::io::append_started(&appends, &child); } if self.spawn_only { self.spawned = Some(child); diff --git a/src/io.rs b/src/io.rs index 81c191f..0ba2efd 100644 --- a/src/io.rs +++ b/src/io.rs @@ -541,9 +541,11 @@ impl Fds { /// `shared_append`). struct AppendFile { file: Arc, - /// Programs it was handed to, by process id. It stays shared while they run, even after - /// the redirection that started them is gone (`cmd >> log &`). - children: Vec, + /// Programs it was handed to. It stays shared while they run, even after the redirection + /// that started them is gone (`cmd >> log &`). Process handles rather than ids: Windows + /// reuses an id once its process is gone, and an unrelated process with it would keep the + /// file open. + children: Vec, } static APPEND_FILES: Mutex> = Mutex::new(Vec::new()); @@ -566,11 +568,13 @@ pub fn shared_append(f: File) -> Arc { file } -/// Record that the program `pid` was started with these `>>` handles. -pub fn append_started(files: &[Arc], pid: u32) { +/// Record that `child` was started with these `>>` handles. +pub fn append_started(files: &[Arc], child: &std::process::Child) { let mut open = APPEND_FILES.lock().unwrap(); for a in open.iter_mut().filter(|a| files.iter().any(|f| Arc::ptr_eq(f, &a.file))) { - a.children.push(pid); + if let Ok(h) = child.as_handle().try_clone_to_owned() { + a.children.push(h); + } } } @@ -584,7 +588,7 @@ pub fn prune_append_files() { fn prune_append(open: &mut Vec) { open.retain_mut(|a| { - a.children.retain(|&pid| sys::pid_alive(pid)); + a.children.retain(|h| sys::process_running(h.as_raw_handle() as sys::HANDLE)); Arc::strong_count(&a.file) > 1 || !a.children.is_empty() }); } diff --git a/src/sys.rs b/src/sys.rs index e8a4d81..f133f02 100644 --- a/src/sys.rs +++ b/src/sys.rs @@ -359,6 +359,11 @@ pub fn kill_pid(pid: u32, code: u32) -> bool { } } +/// Whether the process behind a handle we hold is still running. +pub fn process_running(h: HANDLE) -> bool { + unsafe { WaitForSingleObject(h, 0) != WAIT_OBJECT_0 } +} + pub fn pid_alive(pid: u32) -> bool { unsafe { let h = OpenProcess(SYNCHRONIZE, 0, pid);