Debian Codegraph @

src/sys/windows.rs

raw symbols SCIP
1 use std::io;
2 use std::os::windows::io::{AsRawHandle, RawHandle};
3 use std::process::Child;
4 use windows_sys::Win32::Foundation::{HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT};
5 use windows_sys::Win32::System::Threading::{WaitForSingleObject, INFINITE};
6
7 #[derive(Copy, Clone)]
8 pub struct Handle(RawHandle);
9
10 // Kind of like a child PID on Unix, it's important not to keep the handle
11 // around after the child has been cleaned up. The best solution would be to
12 // have the handle actually borrow the child, but we need to keep the child
13 // unborrowed. Instead we just avoid storing them.
14 pub fn get_handle(child: &Child) -> Handle {
15 Handle(child.as_raw_handle())
16 }
17
18 // This is very similar to libstd's Child::wait implementation, because the basic wait on Windows
19 // doesn't reap. (There's no such thing as reaping child processes on Windows. Instead, you close
20 // the child handle when you're done with it, like a file. These function names are just for
21 // consistency with the Unix side of things). The main difference is that this can be called
22 // without &mut Child.
23 pub fn wait_noreap(handle: Handle) -> io::Result<()> {
24 let wait_ret = unsafe { WaitForSingleObject(handle.0 as HANDLE, INFINITE) };
25 match wait_ret {
26 WAIT_OBJECT_0 => Ok(()),
27 _ => Err(io::Error::last_os_error()),
28 }
29 }
30
31 pub fn try_wait_noreap(handle: Handle) -> io::Result<bool> {
32 let wait_ret = unsafe { WaitForSingleObject(handle.0 as HANDLE, 0) };
33 if wait_ret == WAIT_OBJECT_0 {
34 // The child has exited.
35 Ok(true)
36 } else if wait_ret == WAIT_TIMEOUT {
37 // The child has not exited yet.
38 Ok(false)
39 } else {
40 Err(io::Error::last_os_error())
41 }
42 }
43
44 // Again there's no such thing as "reaping" a child process on Windows, and these function names is
45 // just for consistency with the Unix side of things.
46 #[cfg(feature = "timeout")]
47 pub fn wait_deadline_noreap(handle: Handle, deadline: std::time::Instant) -> io::Result<bool> {
48 let timeout = deadline.saturating_duration_since(std::time::Instant::now());
49 // Convert to milliseconds, rounding *up*. (That way we don't repeatedly sleep for 0ms when
50 // we're close to the timeout.)
51 let timeout_ms = (timeout.as_nanos().saturating_add(999_999) / 1_000_000)
52 .try_into()
53 .unwrap_or(u32::MAX);
54 let wait_ret = unsafe { WaitForSingleObject(handle.0 as HANDLE, timeout_ms) };
55 use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
56 match wait_ret {
57 WAIT_OBJECT_0 => Ok(true),
58 WAIT_TIMEOUT => Ok(false),
59 _ => Err(io::Error::last_os_error()),
60 }
61 }