sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::path::Path;
use std::process::ExitStatus;

use crate::common::DiskUsage;
use crate::{
    CGroupLimits, Error, Gid, KillError, Pid, ProcessInner, ProcessStatus, Signal, ThreadKind, Uid,
};

/// Contains information about a process.
#[doc = include_str!("../../docs/snippets/process.md")]
pub struct Process {
    pub(crate) inner: ProcessInner,
}

impl Process {
    /// Sends [`Signal::Kill`] to the process.
    pub fn kill(&self) -> bool {
        self.kill_with(Signal::Kill).unwrap_or(false)
    }

    /// Sends `signal` to the process.
    pub fn kill_with(&self, signal: Signal) -> Option<bool> {
        self.inner.kill_with(signal)
    }

    /// Sends [`Signal::Kill`] to the process, then waits for termination.
    pub fn kill_and_wait(&self) -> Result<Option<ExitStatus>, KillError> {
        self.kill_with_and_wait(Signal::Kill)
    }

    /// Sends `signal` to the process, then waits for termination.
    pub fn kill_with_and_wait(&self, signal: Signal) -> Result<Option<ExitStatus>, KillError> {
        match self.inner.kill_with(signal) {
            Some(sent) => {
                if !sent {
                    return Err(KillError::FailedToSendSignal);
                }
            }
            None => return Err(KillError::SignalDoesNotExist),
        }

        Ok(self.inner.wait())
    }

    /// Waits for process termination and returns its [`ExitStatus`] when it can be retrieved, or `None` otherwise.
    pub fn wait(&self) -> Option<ExitStatus> {
        self.inner.wait()
    }

    /// Returns the process name.
    pub fn name(&self) -> &OsStr {
        self.inner.name()
    }

    /// Returns the command line.
    pub fn cmd(&self) -> &[OsString] {
        self.inner.cmd()
    }

    /// Returns the path to the process executable.
    pub fn exe(&self) -> Option<&Path> {
        self.inner.exe()
    }

    /// Returns the PID of the process.
    pub fn pid(&self) -> Pid {
        self.inner.pid()
    }

    /// Returns the limits of the process cgroup, or `None` when none exist.
    pub fn cgroup_limits(&self) -> Option<CGroupLimits> {
        self.inner.cgroup_limits()
    }

    /// Returns the environment variables of the process.
    pub fn environ(&self) -> &[OsString] {
        self.inner.environ()
    }

    /// Returns the current working directory.
    pub fn cwd(&self) -> Option<&Path> {
        self.inner.cwd()
    }

    /// Returns the path of the root directory.
    pub fn root(&self) -> Option<&Path> {
        self.inner.root()
    }

    /// Returns the memory usage in bytes.
    pub fn memory(&self) -> u64 {
        self.inner.memory()
    }

    /// Returns the virtual memory usage in bytes.
    pub fn virtual_memory(&self) -> u64 {
        self.inner.virtual_memory()
    }

    /// Returns the parent PID.
    pub fn parent(&self) -> Option<Pid> {
        self.inner.parent()
    }

    /// Returns the process status.
    pub fn status(&self) -> ProcessStatus {
        self.inner.status()
    }

    /// Returns the time the process started, in seconds since the epoch.
    pub fn start_time(&self) -> u64 {
        self.inner.start_time()
    }

    /// Returns how long the process has been running, in seconds.
    pub fn run_time(&self) -> u64 {
        self.inner.run_time()
    }

    /// Returns the total CPU usage in percent.
    pub fn cpu_usage(&self) -> f32 {
        self.inner.cpu_usage()
    }

    /// Returns the total accumulated CPU time in CPU-milliseconds.
    pub fn accumulated_cpu_time(&self) -> u64 {
        self.inner.accumulated_cpu_time()
    }

    /// Returns the number of bytes read from and written to disk.
    pub fn disk_usage(&self) -> DiskUsage {
        self.inner.disk_usage()
    }

    /// Returns the owning user ID, or `None` if unavailable.
    pub fn user_id(&self) -> Option<&Uid> {
        self.inner.user_id()
    }

    /// Returns the effective user ID, or `None` if unavailable.
    pub fn effective_user_id(&self) -> Option<&Uid> {
        self.inner.effective_user_id()
    }

    /// Returns the group ID of the process, or `None` when unavailable.
    ///
    /// Windows currently does not expose the process token's primary group.
    pub fn group_id(&self) -> Option<Gid> {
        self.inner.group_id()
    }

    /// Returns the effective group ID of the process, or `None` when unavailable.
    ///
    /// Windows currently does not expose the process token's primary group.
    pub fn effective_group_id(&self) -> Option<Gid> {
        self.inner.effective_group_id()
    }

    /// Returns the session ID of the process, or `None` if it could not be retrieved.
    pub fn session_id(&self) -> Option<Pid> {
        self.inner.session_id()
    }

    /// Returns the tasks run by this process, or `None` when there are none.
    pub fn tasks(&self) -> Option<&HashSet<Pid>> {
        cfg_select! {
            any(target_os = "linux", target_os = "android") => {
                self.inner.tasks.as_ref()
            }
            _ => {
                None
            }
        }
    }

    /// Returns `Some` with the thread kind when the process is a thread, and `None` otherwise.
    pub fn thread_kind(&self) -> Option<ThreadKind> {
        cfg_select! {
            any(target_os = "linux", target_os = "android") => self.inner.thread_kind(),
            _ => None,
        }
    }

    /// Returns `true` if the process no longer exists but remains in the list because
    /// `remove_dead_processes` was `false` during the last refresh.
    pub fn exists(&self) -> bool {
        self.inner.exists()
    }

    /// Returns the number of open files in the process.
    pub fn open_files(&self) -> Option<usize> {
        self.inner.open_files()
    }

    /// Returns the maximum number of open files for the process.
    pub fn open_files_limit(&self) -> Option<usize> {
        self.inner.open_files_limit()
    }

    /// Returns the total GPU usage of this process, as a percentage across all GPUs.
    #[cfg(feature = "gpu")]
    pub fn gpu_usage(&self) -> Option<f32> {
        self.inner.gpu_usage()
    }

    /// Returns the GPU memory used by this process across all GPUs, in bytes.
    #[cfg(feature = "gpu")]
    pub fn gpu_memory(&self) -> Option<u64> {
        self.inner.gpu_memory()
    }
}

/// Returns the PID of the current process.
#[allow(clippy::unnecessary_wraps)]
pub fn get_current_pid() -> Result<Pid, Error> {
    Ok(Pid::from(std::process::id() as usize))
}