devela::_dep::sysinfo

Struct Process

pub struct Process { /* private fields */ }
Available on crate feature dep_sysinfo only.
Expand description

Struct containing information of a process.

§iOS

This information cannot be retrieved on iOS due to sandboxing.

§Apple app store

If you are building a macOS Apple app store, it won’t be able to retrieve this information.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.name());
}

Implementations§

§

impl Process

pub fn kill(&self) -> bool

Sends Signal::Kill to the process (which is the only signal supported on all supported platforms by this crate).

Returns true if the signal was sent successfully. If you want to wait for this process to end, you can use Process::wait.

⚠️ Even if this function returns true, it doesn’t necessarily mean that the process will be killed. It just means that the signal was sent successfully.

⚠️ Please note that some processes might not be “killable”, like if they run with higher levels than the current process for example.

If you want to use another signal, take a look at Process::kill_with.

To get the list of the supported signals on this system, use SUPPORTED_SIGNALS.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    process.kill();
}

pub fn kill_with(&self, signal: Signal) -> Option<bool>

Sends the given signal to the process. If the signal doesn’t exist on this platform, it’ll do nothing and will return None. Otherwise it’ll return Some(bool). The boolean value will depend on whether or not the signal was sent successfully.

If you just want to kill the process, use Process::kill directly. If you want to wait for this process to end, you can use Process::wait.

⚠️ Please note that some processes might not be “killable”, like if they run with higher levels than the current process for example.

To get the list of the supported signals on this system, use SUPPORTED_SIGNALS.

use sysinfo::{Pid, Signal, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    if process.kill_with(Signal::Kill).is_none() {
        println!("This signal isn't supported on this platform");
    }
}

pub fn wait(&self)

Wait for process termination.

use sysinfo::{Pid, System};

let mut s = System::new_all();

if let Some(process) = s.process(Pid::from(1337)) {
    println!("Waiting for pid 1337");
    process.wait();
    println!("Pid 1337 exited");
}

pub fn name(&self) -> &OsStr

Returns the name of the process.

⚠️ Important ⚠️

On Linux, there are two things to know about processes’ name:

  1. It is limited to 15 characters.
  2. It is not always the exe name.

If you are looking for a specific process, unless you know what you are doing, in most cases it’s better to use Process::exe instead (which can be empty sometimes!).

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.name());
}

pub fn cmd(&self) -> &[OsString]

Returns the command line.

⚠️ Important ⚠️

On Windows, you might need to use administrator privileges when running your program to have access to this information.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.cmd());
}

pub fn exe(&self) -> Option<&Path>

Returns the path to the process.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.exe());
}
§Implementation notes

On Linux, this method will return an empty path if there was an error trying to read /proc/<pid>/exe. This can happen, for example, if the permission levels or UID namespaces between the caller and target processes are different.

It is also the case that cmd[0] is not usually a correct replacement for this. A process may change its cmd[0] value freely, making this an untrustworthy source of information.

pub fn pid(&self) -> Pid

Returns the PID of the process.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{}", process.pid());
}

pub fn environ(&self) -> &[OsString]

Returns the environment variables of the process.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.environ());
}

pub fn cwd(&self) -> Option<&Path>

Returns the current working directory.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.cwd());
}

pub fn root(&self) -> Option<&Path>

Returns the path of the root directory.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.root());
}

pub fn memory(&self) -> u64

Returns the memory usage (in bytes).

This method returns the size of the resident set, that is, the amount of memory that the process allocated and which is currently mapped in physical RAM. It does not include memory that is swapped out, or, in some operating systems, that has been allocated but never used.

Thus, it represents exactly the amount of physical RAM that the process is using at the present time, but it might not be a good indicator of the total memory that the process will be using over its lifetime. For that purpose, you can try and use virtual_memory.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{} bytes", process.memory());
}

pub fn virtual_memory(&self) -> u64

Returns the virtual memory usage (in bytes).

This method returns the size of virtual memory, that is, the amount of memory that the process can access, whether it is currently mapped in physical RAM or not. It includes physical RAM, allocated but not used regions, swapped-out regions, and even memory associated with memory-mapped files.

This value has limitations though. Depending on the operating system and type of process, this value might be a good indicator of the total memory that the process will be using over its lifetime. However, for example, in the version 14 of macOS this value is in the order of the hundreds of gigabytes for every process, and thus not very informative. Moreover, if a process maps into memory a very large file, this value will increase accordingly, even if the process is not actively using the memory.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{} bytes", process.virtual_memory());
}

pub fn parent(&self) -> Option<Pid>

Returns the parent PID.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.parent());
}

pub fn status(&self) -> ProcessStatus

Returns the status of the process.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.status());
}

pub fn start_time(&self) -> u64

Returns the time where the process was started (in seconds) from epoch.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("Started at {} seconds", process.start_time());
}

pub fn run_time(&self) -> u64

Returns for how much time the process has been running (in seconds).

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("Running since {} seconds", process.run_time());
}

pub fn cpu_usage(&self) -> f32

Returns the total CPU usage (in %). Notice that it might be bigger than 100 if run on a multi-core machine.

If you want a value between 0% and 100%, divide the returned value by the number of CPUs.

⚠️ To start to have accurate CPU usage, a process needs to be refreshed twice because CPU usage computation is based on time diff (process time on a given time period divided by total system time on the same time period).

⚠️ If you want accurate CPU usage number, better leave a bit of time between two calls of this method (take a look at MINIMUM_CPU_UPDATE_INTERVAL for more information).

use sysinfo::{Pid, ProcessesToUpdate, ProcessRefreshKind, System};

let mut s = System::new_all();
// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPU usage to get actual value.
s.refresh_processes_specifics(
    ProcessesToUpdate::All,
    true,
    ProcessRefreshKind::nothing().with_cpu()
);
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{}%", process.cpu_usage());
}

pub fn disk_usage(&self) -> DiskUsage

Returns number of bytes read and written to disk.

⚠️ On Windows, this method actually returns ALL I/O read and written bytes.

⚠️ Files might be cached in memory by your OS, meaning that reading/writing them might not increase the read_bytes/written_bytes values. You can find more information about it in the proc_pid_io manual (man proc_pid_io on unix platforms).

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    let disk_usage = process.disk_usage();
    println!("read bytes   : new/total => {}/{}",
        disk_usage.read_bytes,
        disk_usage.total_read_bytes,
    );
    println!("written bytes: new/total => {}/{}",
        disk_usage.written_bytes,
        disk_usage.total_written_bytes,
    );
}

pub fn user_id(&self) -> Option<&Uid>

Returns the ID of the owner user of this process or None if this information couldn’t be retrieved. If you want to get the User from it, take a look at Users::get_user_by_id.

use sysinfo::{Pid, System};

let mut s = System::new_all();

if let Some(process) = s.process(Pid::from(1337)) {
    println!("User id for process 1337: {:?}", process.user_id());
}

pub fn effective_user_id(&self) -> Option<&Uid>

Returns the user ID of the effective owner of this process or None if this information couldn’t be retrieved. If you want to get the User from it, take a look at Users::get_user_by_id.

If you run something with sudo, the real user ID of the launched process will be the ID of the user you are logged in as but effective user ID will be 0 (i-e root).

⚠️ It always returns None on Windows.

use sysinfo::{Pid, System};

let mut s = System::new_all();

if let Some(process) = s.process(Pid::from(1337)) {
    println!("User id for process 1337: {:?}", process.effective_user_id());
}

pub fn group_id(&self) -> Option<Gid>

Returns the process group ID of the process.

⚠️ It always returns None on Windows.

use sysinfo::{Pid, System};

let mut s = System::new_all();

if let Some(process) = s.process(Pid::from(1337)) {
    println!("Group ID for process 1337: {:?}", process.group_id());
}

pub fn effective_group_id(&self) -> Option<Gid>

Returns the effective group ID of the process.

If you run something with sudo, the real group ID of the launched process will be the primary group ID you are logged in as but effective group ID will be 0 (i-e root).

⚠️ It always returns None on Windows.

use sysinfo::{Pid, System};

let mut s = System::new_all();

if let Some(process) = s.process(Pid::from(1337)) {
    println!("User id for process 1337: {:?}", process.effective_group_id());
}

pub fn session_id(&self) -> Option<Pid>

Returns the session ID for the current process or None if it couldn’t be retrieved.

⚠️ This information is computed every time this method is called.

use sysinfo::{Pid, System};

let mut s = System::new_all();

if let Some(process) = s.process(Pid::from(1337)) {
    println!("Session ID for process 1337: {:?}", process.session_id());
}

pub fn tasks(&self) -> Option<&HashSet<Pid>>

Tasks run by this process. If there are none, returns None.

⚠️ This method always returns None on other platforms than Linux.

use sysinfo::{Pid, System};

let mut s = System::new_all();

if let Some(process) = s.process(Pid::from(1337)) {
    if let Some(tasks) = process.tasks() {
        println!("Listing tasks for process {:?}", process.pid());
        for task_pid in tasks {
            if let Some(task) = s.process(*task_pid) {
                println!("Task {:?}: {:?}", task.pid(), task.name());
            }
        }
    }
}

pub fn thread_kind(&self) -> Option<ThreadKind>

If the process is a thread, it’ll return Some with the kind of thread it is. Returns None otherwise.

⚠️ This method always returns None on other platforms than Linux.

use sysinfo::System;

let s = System::new_all();

for (_, process) in s.processes() {
    if let Some(thread_kind) = process.thread_kind() {
        println!("Process {:?} is a {thread_kind:?} thread", process.pid());
    }
}

Trait Implementations§

§

impl Debug for Process

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> ArchivePointee for T

§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ByteSized for T

Source§

const BYTE_ALIGN: usize = _

The alignment of this type in bytes.
Source§

const BYTE_SIZE: usize = _

The size of this type in bytes.
Source§

fn byte_align(&self) -> usize

Returns the alignment of this type in bytes.
Source§

fn byte_size(&self) -> usize

Returns the size of this type in bytes. Read more
Source§

fn ptr_size_ratio(&self) -> [usize; 2]

Returns the size ratio between Ptr::BYTES and BYTE_SIZE. Read more
Source§

impl<T, R> Chain<R> for T
where T: ?Sized,

Source§

fn chain<F>(self, f: F) -> R
where F: FnOnce(Self) -> R, Self: Sized,

Chain a function which takes the parameter by value.
Source§

fn chain_ref<F>(&self, f: F) -> R
where F: FnOnce(&Self) -> R,

Chain a function which takes the parameter by shared reference.
Source§

fn chain_mut<F>(&mut self, f: F) -> R
where F: FnOnce(&mut Self) -> R,

Chain a function which takes the parameter by exclusive reference.
Source§

impl<T> ExtAny for T
where T: Any + ?Sized,

Source§

fn type_id() -> TypeId

Returns the TypeId of Self. Read more
Source§

fn type_of(&self) -> TypeId

Returns the TypeId of self. Read more
Source§

fn type_name(&self) -> &'static str

Returns the type name of self. Read more
Source§

fn type_is<T: 'static>(&self) -> bool

Returns true if Self is of type T. Read more
Source§

fn as_any_ref(&self) -> &dyn Any
where Self: Sized,

Upcasts &self as &dyn Any. Read more
Source§

fn as_any_mut(&mut self) -> &mut dyn Any
where Self: Sized,

Upcasts &mut self as &mut dyn Any. Read more
Source§

fn as_any_box(self: Box<Self>) -> Box<dyn Any>
where Self: Sized,

Upcasts Box<self> as Box<dyn Any>. Read more
Source§

fn downcast_ref<T: 'static>(&self) -> Option<&T>

Available on crate feature unsafe_layout only.
Returns some shared reference to the inner value if it is of type T. Read more
Source§

fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T>

Available on crate feature unsafe_layout only.
Returns some exclusive reference to the inner value if it is of type T. Read more
Source§

impl<T> ExtMem for T
where T: ?Sized,

Source§

const NEEDS_DROP: bool = _

Know whether dropping values of this type matters, in compile-time.
Source§

fn mem_align_of<T>() -> usize

Returns the minimum alignment of the type in bytes. Read more
Source§

fn mem_align_of_val(&self) -> usize

Returns the alignment of the pointed-to value in bytes. Read more
Source§

fn mem_size_of<T>() -> usize

Returns the size of a type in bytes. Read more
Source§

fn mem_size_of_val(&self) -> usize

Returns the size of the pointed-to value in bytes. Read more
Source§

fn mem_copy(&self) -> Self
where Self: Copy,

Bitwise-copies a value. Read more
Source§

fn mem_needs_drop(&self) -> bool

Returns true if dropping values of this type matters. Read more
Source§

fn mem_drop(self)
where Self: Sized,

Drops self by running its destructor. Read more
Source§

fn mem_forget(self)
where Self: Sized,

Forgets about self without running its destructor. Read more
Source§

fn mem_replace(&mut self, other: Self) -> Self
where Self: Sized,

Replaces self with other, returning the previous value of self. Read more
Source§

fn mem_take(&mut self) -> Self
where Self: Default,

Replaces self with its default value, returning the previous value of self. Read more
Source§

fn mem_swap(&mut self, other: &mut Self)
where Self: Sized,

Swaps the value of self and other without deinitializing either one. Read more
Source§

unsafe fn mem_zeroed<T>() -> T

Available on crate feature unsafe_layout only.
Returns the value of type T represented by the all-zero byte-pattern. Read more
Source§

unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst

Available on crate feature unsafe_layout only.
Returns the value of type T represented by the all-zero byte-pattern. Read more
Source§

fn mem_as_bytes(&self) -> &[u8]
where Self: Sync + Unpin,

Available on crate feature unsafe_slice only.
View a Sync + Unpin self as &[u8]. Read more
Source§

fn mem_as_bytes_mut(&mut self) -> &mut [u8]
where Self: Sync + Unpin,

Available on crate feature unsafe_slice only.
View a Sync + Unpin self as &mut [u8]. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

Source§

impl<T> Hook for T

Source§

fn hook_ref<F>(self, f: F) -> Self
where F: FnOnce(&Self),

Applies a function which takes the parameter by shared reference, and then returns the (possibly) modified owned value. Read more
Source§

fn hook_mut<F>(self, f: F) -> Self
where F: FnOnce(&mut Self),

Applies a function which takes the parameter by exclusive reference, and then returns the (possibly) modified owned value. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> LayoutRaw for T

§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Pointee for T

§

type Metadata = ()

The metadata type for pointers and references to this type.
§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

§

fn to_sample_(self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

§

impl<T> Ungil for T
where T: Send,