pub(crate) mod stat_parse;
#[cfg_attr(windows, path = "identity/windows.rs")]
#[cfg_attr(target_os = "linux", path = "identity/linux.rs")]
#[cfg_attr(target_os = "macos", path = "identity/macos.rs")]
mod backend;
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
compile_error!("cosca::identity is implemented only for Windows, Linux, and macOS");
pub type RawPid = u32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct StartToken(u64);
impl StartToken {
fn from_raw(v: u64) -> StartToken {
StartToken(v)
}
fn raw(self) -> u64 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ProcessId {
pid: RawPid,
start: StartToken,
}
impl ProcessId {
pub fn pid(&self) -> RawPid {
self.pid
}
pub(crate) fn start_token_raw(&self) -> u64 {
self.start.raw()
}
pub fn of(pid: RawPid) -> Option<ProcessId> {
let start = backend::start_token(pid)?;
Some(ProcessId { pid, start })
}
#[cfg(test)]
pub(crate) fn from_parts_for_test(pid: RawPid, token: u64) -> ProcessId {
ProcessId {
pid,
start: StartToken::from_raw(token),
}
}
pub fn current() -> ProcessId {
let pid = std::process::id();
ProcessId::of(pid).expect("the current process always has a resolvable identity")
}
pub fn exists(&self) -> bool {
backend::start_token(self.pid) == Some(self.start)
}
pub fn is_alive(&self) -> bool {
backend::is_running(self.pid, self.start)
}
pub fn created_at(&self) -> Option<std::time::SystemTime> {
backend::created_at(self.start)
}
}
#[cfg(windows)]
pub(crate) fn windows_handle_is(handle: windows::Win32::Foundation::HANDLE, id: ProcessId) -> bool {
backend::creation_token(handle) == Some(id.start)
}
#[cfg(windows)]
pub(crate) fn windows_identity_from_handle(
handle: windows::Win32::Foundation::HANDLE,
pid: RawPid,
) -> Option<ProcessId> {
backend::windows_identity_from_handle(handle, pid)
}
#[cfg(test)]
#[path = "identity_tests.rs"]
mod identity_tests;