Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
18 changes: 11 additions & 7 deletions src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,9 +541,11 @@ impl Fds {
/// `shared_append`).
struct AppendFile {
file: Arc<File>,
/// 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<u32>,
/// 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<std::os::windows::io::OwnedHandle>,
}

static APPEND_FILES: Mutex<Vec<AppendFile>> = Mutex::new(Vec::new());
Expand All @@ -566,11 +568,13 @@ pub fn shared_append(f: File) -> Arc<File> {
file
}

/// Record that the program `pid` was started with these `>>` handles.
pub fn append_started(files: &[Arc<File>], pid: u32) {
/// Record that `child` was started with these `>>` handles.
pub fn append_started(files: &[Arc<File>], 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);
}
}
}

Expand All @@ -584,7 +588,7 @@ pub fn prune_append_files() {

fn prune_append(open: &mut Vec<AppendFile>) {
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()
});
}
5 changes: 5 additions & 0 deletions src/sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading