use std::os::windows::process::ExitStatusExt;
use std::process::ExitStatus;
#[cfg(feature = "debug")]
use std::io;
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::System::RemoteDesktop::ProcessIdToSessionId;
use windows::Win32::System::Threading::{
GetExitCodeProcess, GetProcessHandleCount, INFINITE, OpenProcess, PROCESS_SYNCHRONIZE,
WaitForSingleObject,
};
use crate::Pid;
use crate::sys::system::is_proc_running;
use crate::sys::utils::HandleWrapper;
use super::ProcessInner;
impl ProcessInner {
pub(crate) fn wait(&self) -> Option<ExitStatus> {
if let Some(handle) = self.get_handle() {
let mut need_fallback = true;
match HandleWrapper::new(unsafe {
OpenProcess(PROCESS_SYNCHRONIZE, false, self.pid.0 as u32).unwrap_or_default()
}) {
Some(sync_handle) => {
if unsafe { WaitForSingleObject(*sync_handle, INFINITE) } != WAIT_OBJECT_0 {
sinf_debug!(
"`WaitForSingleObject` failed: {:?}. Using fallback",
io::Error::last_os_error()
);
} else {
need_fallback = false;
}
}
None => {
sinf_debug!(
"OpenProcess with `PROCESS_SYNCHRONIZE` failed: {:?}. Using fallback",
io::Error::last_os_error()
);
}
}
if need_fallback {
while is_proc_running(handle) {
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
let mut exit_status = 0;
unsafe {
match GetExitCodeProcess(handle, &mut exit_status) {
Ok(_) => Some(ExitStatus::from_raw(exit_status)),
Err(_error) => {
sinf_debug!("failed to retrieve process exit status: {_error:?}");
None
}
}
}
} else {
sinf_debug!("can't wait on this process so returning");
None
}
}
pub(crate) fn session_id(&self) -> Option<Pid> {
unsafe {
let mut out = 0;
if ProcessIdToSessionId(self.pid.as_u32(), &mut out).is_ok() {
return Some(Pid(out as _));
}
sinf_debug!(
"ProcessIdToSessionId failed, error: {:?}",
io::Error::last_os_error()
);
None
}
}
pub(crate) fn switch_updated(&mut self) -> bool {
std::mem::replace(&mut self.updated, false)
}
pub(crate) fn set_nonexistent(&mut self) {
self.exists = false;
}
pub(crate) fn exists(&self) -> bool {
self.exists
}
pub(crate) fn open_files(&self) -> Option<usize> {
if let Some(ref handle) = self.handle {
let mut handles_count = 0;
unsafe {
if let Err(_error) = GetProcessHandleCount(***handle, &mut handles_count) {
sinf_debug!("GetProcessHandleCount failed: {_error:?}");
None
} else {
Some(handles_count as _)
}
}
} else {
None
}
}
pub(crate) fn open_files_limit(&self) -> Option<usize> {
crate::System::open_files_limit().ok()
}
#[cfg(feature = "gpu")]
pub(crate) fn gpu_usage(&self) -> Option<f32> {
self.gpu_info.gpu_usage
}
#[cfg(feature = "gpu")]
pub fn gpu_memory(&self) -> Option<u64> {
self.gpu_info.gpu_memory
}
}