Struct Process

Source
pub struct Process { /* private fields */ }
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§

Source§

impl Process

Source

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 or directly Process::kill_and_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();
}
Source

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 or Process::kill_with_and_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");
    }
}
Examples found in repository?
examples/simple.rs (line 238)
65fn interpret_input(
66    input: &str,
67    sys: &mut System,
68    networks: &mut Networks,
69    disks: &mut Disks,
70    components: &mut Components,
71    users: &mut Users,
72) -> bool {
73    match input.trim() {
74        "help" => print_help(),
75        "refresh_disks" => {
76            println!("Refreshing disk list...");
77            disks.refresh(true);
78            println!("Done.");
79        }
80        "refresh_users" => {
81            println!("Refreshing user list...");
82            users.refresh();
83            println!("Done.");
84        }
85        "refresh_networks" => {
86            println!("Refreshing network list...");
87            networks.refresh(true);
88            println!("Done.");
89        }
90        "refresh_components" => {
91            println!("Refreshing component list...");
92            components.refresh(true);
93            println!("Done.");
94        }
95        "refresh_cpu" => {
96            println!("Refreshing CPUs...");
97            sys.refresh_cpu_all();
98            println!("Done.");
99        }
100        "signals" => {
101            for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
102                println!("{:2}:{sig:?}", nb + 1);
103            }
104        }
105        "cpus" => {
106            // Note: you should refresh a few times before using this, so that usage statistics
107            // can be ascertained
108            println!(
109                "number of physical cores: {}",
110                System::physical_core_count()
111                    .map(|c| c.to_string())
112                    .unwrap_or_else(|| "Unknown".to_owned()),
113            );
114            println!("total CPU usage: {}%", sys.global_cpu_usage(),);
115            for cpu in sys.cpus() {
116                println!("{cpu:?}");
117            }
118        }
119        "memory" => {
120            println!("total memory:     {: >10} KB", sys.total_memory() / 1_000);
121            println!(
122                "available memory: {: >10} KB",
123                sys.available_memory() / 1_000
124            );
125            println!("used memory:      {: >10} KB", sys.used_memory() / 1_000);
126            println!("total swap:       {: >10} KB", sys.total_swap() / 1_000);
127            println!("used swap:        {: >10} KB", sys.used_swap() / 1_000);
128        }
129        "quit" | "exit" => return true,
130        "all" => {
131            for (pid, proc_) in sys.processes() {
132                println!(
133                    "{}:{} status={:?}",
134                    pid,
135                    proc_.name().to_string_lossy(),
136                    proc_.status()
137                );
138            }
139        }
140        "frequency" => {
141            for cpu in sys.cpus() {
142                println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
143            }
144        }
145        "vendor_id" => {
146            println!("vendor ID: {}", sys.cpus()[0].vendor_id());
147        }
148        "brand" => {
149            println!("brand: {}", sys.cpus()[0].brand());
150        }
151        "load_avg" => {
152            let load_avg = System::load_average();
153            println!("one minute     : {}%", load_avg.one);
154            println!("five minutes   : {}%", load_avg.five);
155            println!("fifteen minutes: {}%", load_avg.fifteen);
156        }
157        e if e.starts_with("show ") => {
158            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
159
160            if tmp.len() != 2 {
161                println!("show command takes a pid or a name in parameter!");
162                println!("example: show 1254");
163            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
164                match sys.process(pid) {
165                    Some(p) => {
166                        println!("{:?}", *p);
167                        println!(
168                            "Files open/limit: {:?}/{:?}",
169                            p.open_files(),
170                            p.open_files_limit(),
171                        );
172                    }
173                    None => {
174                        println!("pid \"{pid:?}\" not found");
175                    }
176                }
177            } else {
178                let proc_name = tmp[1];
179                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
180                    println!("==== {} ====", proc_.name().to_string_lossy());
181                    println!("{proc_:?}");
182                }
183            }
184        }
185        "temperature" => {
186            for component in components.iter() {
187                println!("{component:?}");
188            }
189        }
190        "network" => {
191            for (interface_name, data) in networks.iter() {
192                println!(
193                    "\
194{interface_name}:
195  ether {}
196  input data  (new / total): {} / {} B
197  output data (new / total): {} / {} B",
198                    data.mac_address(),
199                    data.received(),
200                    data.total_received(),
201                    data.transmitted(),
202                    data.total_transmitted(),
203                );
204            }
205        }
206        "show" => {
207            println!("'show' command expects a pid number or a process name");
208        }
209        e if e.starts_with("kill ") => {
210            let tmp: Vec<&str> = e
211                .split(' ')
212                .map(|s| s.trim())
213                .filter(|s| !s.is_empty())
214                .collect();
215
216            if tmp.len() != 3 {
217                println!("kill command takes the pid and a signal number in parameter!");
218                println!("example: kill 1254 9");
219            } else {
220                let Ok(pid) = Pid::from_str(tmp[1]) else {
221                    eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
222                    return false;
223                };
224                let Ok(signal) = usize::from_str(tmp[2]) else {
225                    eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
226                    return false;
227                };
228                let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
229                    eprintln!(
230                        "No signal matching {signal}. Use the `signals` command to get the \
231                         list of signals.",
232                    );
233                    return false;
234                };
235
236                match sys.process(pid) {
237                    Some(p) => {
238                        if let Some(res) = p.kill_with(*signal) {
239                            println!("kill: {res}");
240                        } else {
241                            eprintln!("kill: signal not supported on this platform");
242                        }
243                    }
244                    None => {
245                        eprintln!("pid not found");
246                    }
247                }
248            }
249        }
250        "disks" => {
251            for disk in disks {
252                println!("{disk:?}");
253            }
254        }
255        "users" => {
256            for user in users {
257                println!("{:?} => {:?}", user.name(), user.groups(),);
258            }
259        }
260        "groups" => {
261            for group in Groups::new_with_refreshed_list().list() {
262                println!("{group:?}");
263            }
264        }
265        "boot_time" => {
266            println!("{} seconds", System::boot_time());
267        }
268        "uptime" => {
269            let up = System::uptime();
270            let mut uptime = up;
271            let days = uptime / 86400;
272            uptime -= days * 86400;
273            let hours = uptime / 3600;
274            uptime -= hours * 3600;
275            let minutes = uptime / 60;
276            println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
277        }
278        x if x.starts_with("refresh") => {
279            if x == "refresh" {
280                println!("Getting processes' information...");
281                sys.refresh_all();
282                println!("Done.");
283            } else if x.starts_with("refresh ") {
284                println!("Getting process' information...");
285                if let Some(pid) = x
286                    .split(' ')
287                    .filter_map(|pid| pid.parse().ok())
288                    .take(1)
289                    .next()
290                {
291                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
292                        println!("Process `{pid}` updated successfully");
293                    } else {
294                        println!("Process `{pid}` couldn't be updated...");
295                    }
296                } else {
297                    println!("Invalid [pid] received...");
298                }
299            } else {
300                println!(
301                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
302                     list.",
303                );
304            }
305        }
306        "pid" => {
307            println!(
308                "PID: {}",
309                sysinfo::get_current_pid().expect("failed to get PID")
310            );
311        }
312        "system" => {
313            println!(
314                "System name:              {}\n\
315                 System kernel version:    {}\n\
316                 System OS version:        {}\n\
317                 System OS (long) version: {}\n\
318                 System host name:         {}\n\
319                 System kernel:            {}",
320                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
321                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
322                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
323                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
324                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
325                System::kernel_long_version(),
326            );
327        }
328        e => {
329            println!(
330                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
331                 list.",
332            );
333        }
334    }
335    false
336}
Source

pub fn kill_and_wait(&self) -> Result<Option<ExitStatus>, KillError>

Sends Signal::Kill to the process then waits for its termination.

Internally, this method is calling Process::kill then Process::wait.

⚠️ Please note that some processes might not be “killable”, like if they run with higher levels than the current process for example. In this case, this method could enter an infinite loop.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    if let Err(error) = process.kill_and_wait() {
        println!("`kill_and_wait` failed: {error:?}");
    }
}
Source

pub fn kill_with_and_wait( &self, signal: Signal, ) -> Result<Option<ExitStatus>, KillError>

Sends the given signal to the process.then waits for its termination.

Internally, this method is calling Process::kill_with then Process::wait.

⚠️ Please note that some processes might not be “killable”, like if they run with higher levels than the current process for example. In this case, this method could enter an infinite loop.

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)) {
    if let Err(error) = process.kill_and_wait() {
        println!("`kill_and_wait` failed: {error:?}");
    }
}
Source

pub fn wait(&self) -> Option<ExitStatus>

Waits for process termination and returns its [ExitStatus] if it could be retrieved, returns None otherwise. It means that as long as the process is alive, this method will not return.

⚠️ On macOS and FreeBSD, if the process died and a new one took its PID, unless you refreshed, it will wait for the new process to end.

On Windows, as long as we have a (internal) handle, we can always retrieve the exit status.

On Linux/Android, we check that the start time of the PID we’re waiting is the same as the current process’. If not it means the process died and a new one got its PID.

use sysinfo::{Pid, System};

let mut s = System::new_all();

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

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());
}
Examples found in repository?
examples/simple.rs (line 135)
65fn interpret_input(
66    input: &str,
67    sys: &mut System,
68    networks: &mut Networks,
69    disks: &mut Disks,
70    components: &mut Components,
71    users: &mut Users,
72) -> bool {
73    match input.trim() {
74        "help" => print_help(),
75        "refresh_disks" => {
76            println!("Refreshing disk list...");
77            disks.refresh(true);
78            println!("Done.");
79        }
80        "refresh_users" => {
81            println!("Refreshing user list...");
82            users.refresh();
83            println!("Done.");
84        }
85        "refresh_networks" => {
86            println!("Refreshing network list...");
87            networks.refresh(true);
88            println!("Done.");
89        }
90        "refresh_components" => {
91            println!("Refreshing component list...");
92            components.refresh(true);
93            println!("Done.");
94        }
95        "refresh_cpu" => {
96            println!("Refreshing CPUs...");
97            sys.refresh_cpu_all();
98            println!("Done.");
99        }
100        "signals" => {
101            for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
102                println!("{:2}:{sig:?}", nb + 1);
103            }
104        }
105        "cpus" => {
106            // Note: you should refresh a few times before using this, so that usage statistics
107            // can be ascertained
108            println!(
109                "number of physical cores: {}",
110                System::physical_core_count()
111                    .map(|c| c.to_string())
112                    .unwrap_or_else(|| "Unknown".to_owned()),
113            );
114            println!("total CPU usage: {}%", sys.global_cpu_usage(),);
115            for cpu in sys.cpus() {
116                println!("{cpu:?}");
117            }
118        }
119        "memory" => {
120            println!("total memory:     {: >10} KB", sys.total_memory() / 1_000);
121            println!(
122                "available memory: {: >10} KB",
123                sys.available_memory() / 1_000
124            );
125            println!("used memory:      {: >10} KB", sys.used_memory() / 1_000);
126            println!("total swap:       {: >10} KB", sys.total_swap() / 1_000);
127            println!("used swap:        {: >10} KB", sys.used_swap() / 1_000);
128        }
129        "quit" | "exit" => return true,
130        "all" => {
131            for (pid, proc_) in sys.processes() {
132                println!(
133                    "{}:{} status={:?}",
134                    pid,
135                    proc_.name().to_string_lossy(),
136                    proc_.status()
137                );
138            }
139        }
140        "frequency" => {
141            for cpu in sys.cpus() {
142                println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
143            }
144        }
145        "vendor_id" => {
146            println!("vendor ID: {}", sys.cpus()[0].vendor_id());
147        }
148        "brand" => {
149            println!("brand: {}", sys.cpus()[0].brand());
150        }
151        "load_avg" => {
152            let load_avg = System::load_average();
153            println!("one minute     : {}%", load_avg.one);
154            println!("five minutes   : {}%", load_avg.five);
155            println!("fifteen minutes: {}%", load_avg.fifteen);
156        }
157        e if e.starts_with("show ") => {
158            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
159
160            if tmp.len() != 2 {
161                println!("show command takes a pid or a name in parameter!");
162                println!("example: show 1254");
163            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
164                match sys.process(pid) {
165                    Some(p) => {
166                        println!("{:?}", *p);
167                        println!(
168                            "Files open/limit: {:?}/{:?}",
169                            p.open_files(),
170                            p.open_files_limit(),
171                        );
172                    }
173                    None => {
174                        println!("pid \"{pid:?}\" not found");
175                    }
176                }
177            } else {
178                let proc_name = tmp[1];
179                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
180                    println!("==== {} ====", proc_.name().to_string_lossy());
181                    println!("{proc_:?}");
182                }
183            }
184        }
185        "temperature" => {
186            for component in components.iter() {
187                println!("{component:?}");
188            }
189        }
190        "network" => {
191            for (interface_name, data) in networks.iter() {
192                println!(
193                    "\
194{interface_name}:
195  ether {}
196  input data  (new / total): {} / {} B
197  output data (new / total): {} / {} B",
198                    data.mac_address(),
199                    data.received(),
200                    data.total_received(),
201                    data.transmitted(),
202                    data.total_transmitted(),
203                );
204            }
205        }
206        "show" => {
207            println!("'show' command expects a pid number or a process name");
208        }
209        e if e.starts_with("kill ") => {
210            let tmp: Vec<&str> = e
211                .split(' ')
212                .map(|s| s.trim())
213                .filter(|s| !s.is_empty())
214                .collect();
215
216            if tmp.len() != 3 {
217                println!("kill command takes the pid and a signal number in parameter!");
218                println!("example: kill 1254 9");
219            } else {
220                let Ok(pid) = Pid::from_str(tmp[1]) else {
221                    eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
222                    return false;
223                };
224                let Ok(signal) = usize::from_str(tmp[2]) else {
225                    eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
226                    return false;
227                };
228                let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
229                    eprintln!(
230                        "No signal matching {signal}. Use the `signals` command to get the \
231                         list of signals.",
232                    );
233                    return false;
234                };
235
236                match sys.process(pid) {
237                    Some(p) => {
238                        if let Some(res) = p.kill_with(*signal) {
239                            println!("kill: {res}");
240                        } else {
241                            eprintln!("kill: signal not supported on this platform");
242                        }
243                    }
244                    None => {
245                        eprintln!("pid not found");
246                    }
247                }
248            }
249        }
250        "disks" => {
251            for disk in disks {
252                println!("{disk:?}");
253            }
254        }
255        "users" => {
256            for user in users {
257                println!("{:?} => {:?}", user.name(), user.groups(),);
258            }
259        }
260        "groups" => {
261            for group in Groups::new_with_refreshed_list().list() {
262                println!("{group:?}");
263            }
264        }
265        "boot_time" => {
266            println!("{} seconds", System::boot_time());
267        }
268        "uptime" => {
269            let up = System::uptime();
270            let mut uptime = up;
271            let days = uptime / 86400;
272            uptime -= days * 86400;
273            let hours = uptime / 3600;
274            uptime -= hours * 3600;
275            let minutes = uptime / 60;
276            println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
277        }
278        x if x.starts_with("refresh") => {
279            if x == "refresh" {
280                println!("Getting processes' information...");
281                sys.refresh_all();
282                println!("Done.");
283            } else if x.starts_with("refresh ") {
284                println!("Getting process' information...");
285                if let Some(pid) = x
286                    .split(' ')
287                    .filter_map(|pid| pid.parse().ok())
288                    .take(1)
289                    .next()
290                {
291                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
292                        println!("Process `{pid}` updated successfully");
293                    } else {
294                        println!("Process `{pid}` couldn't be updated...");
295                    }
296                } else {
297                    println!("Invalid [pid] received...");
298                }
299            } else {
300                println!(
301                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
302                     list.",
303                );
304            }
305        }
306        "pid" => {
307            println!(
308                "PID: {}",
309                sysinfo::get_current_pid().expect("failed to get PID")
310            );
311        }
312        "system" => {
313            println!(
314                "System name:              {}\n\
315                 System kernel version:    {}\n\
316                 System OS version:        {}\n\
317                 System OS (long) version: {}\n\
318                 System host name:         {}\n\
319                 System kernel:            {}",
320                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
321                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
322                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
323                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
324                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
325                System::kernel_long_version(),
326            );
327        }
328        e => {
329            println!(
330                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
331                 list.",
332            );
333        }
334    }
335    false
336}
Source

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());
}
Source

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.

Source

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());
}
Source

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());
}
Source

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());
}
Source

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());
}
Source

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());
}
Source

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());
}
Source

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());
}
Source

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());
}
Examples found in repository?
examples/simple.rs (line 136)
65fn interpret_input(
66    input: &str,
67    sys: &mut System,
68    networks: &mut Networks,
69    disks: &mut Disks,
70    components: &mut Components,
71    users: &mut Users,
72) -> bool {
73    match input.trim() {
74        "help" => print_help(),
75        "refresh_disks" => {
76            println!("Refreshing disk list...");
77            disks.refresh(true);
78            println!("Done.");
79        }
80        "refresh_users" => {
81            println!("Refreshing user list...");
82            users.refresh();
83            println!("Done.");
84        }
85        "refresh_networks" => {
86            println!("Refreshing network list...");
87            networks.refresh(true);
88            println!("Done.");
89        }
90        "refresh_components" => {
91            println!("Refreshing component list...");
92            components.refresh(true);
93            println!("Done.");
94        }
95        "refresh_cpu" => {
96            println!("Refreshing CPUs...");
97            sys.refresh_cpu_all();
98            println!("Done.");
99        }
100        "signals" => {
101            for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
102                println!("{:2}:{sig:?}", nb + 1);
103            }
104        }
105        "cpus" => {
106            // Note: you should refresh a few times before using this, so that usage statistics
107            // can be ascertained
108            println!(
109                "number of physical cores: {}",
110                System::physical_core_count()
111                    .map(|c| c.to_string())
112                    .unwrap_or_else(|| "Unknown".to_owned()),
113            );
114            println!("total CPU usage: {}%", sys.global_cpu_usage(),);
115            for cpu in sys.cpus() {
116                println!("{cpu:?}");
117            }
118        }
119        "memory" => {
120            println!("total memory:     {: >10} KB", sys.total_memory() / 1_000);
121            println!(
122                "available memory: {: >10} KB",
123                sys.available_memory() / 1_000
124            );
125            println!("used memory:      {: >10} KB", sys.used_memory() / 1_000);
126            println!("total swap:       {: >10} KB", sys.total_swap() / 1_000);
127            println!("used swap:        {: >10} KB", sys.used_swap() / 1_000);
128        }
129        "quit" | "exit" => return true,
130        "all" => {
131            for (pid, proc_) in sys.processes() {
132                println!(
133                    "{}:{} status={:?}",
134                    pid,
135                    proc_.name().to_string_lossy(),
136                    proc_.status()
137                );
138            }
139        }
140        "frequency" => {
141            for cpu in sys.cpus() {
142                println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
143            }
144        }
145        "vendor_id" => {
146            println!("vendor ID: {}", sys.cpus()[0].vendor_id());
147        }
148        "brand" => {
149            println!("brand: {}", sys.cpus()[0].brand());
150        }
151        "load_avg" => {
152            let load_avg = System::load_average();
153            println!("one minute     : {}%", load_avg.one);
154            println!("five minutes   : {}%", load_avg.five);
155            println!("fifteen minutes: {}%", load_avg.fifteen);
156        }
157        e if e.starts_with("show ") => {
158            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
159
160            if tmp.len() != 2 {
161                println!("show command takes a pid or a name in parameter!");
162                println!("example: show 1254");
163            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
164                match sys.process(pid) {
165                    Some(p) => {
166                        println!("{:?}", *p);
167                        println!(
168                            "Files open/limit: {:?}/{:?}",
169                            p.open_files(),
170                            p.open_files_limit(),
171                        );
172                    }
173                    None => {
174                        println!("pid \"{pid:?}\" not found");
175                    }
176                }
177            } else {
178                let proc_name = tmp[1];
179                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
180                    println!("==== {} ====", proc_.name().to_string_lossy());
181                    println!("{proc_:?}");
182                }
183            }
184        }
185        "temperature" => {
186            for component in components.iter() {
187                println!("{component:?}");
188            }
189        }
190        "network" => {
191            for (interface_name, data) in networks.iter() {
192                println!(
193                    "\
194{interface_name}:
195  ether {}
196  input data  (new / total): {} / {} B
197  output data (new / total): {} / {} B",
198                    data.mac_address(),
199                    data.received(),
200                    data.total_received(),
201                    data.transmitted(),
202                    data.total_transmitted(),
203                );
204            }
205        }
206        "show" => {
207            println!("'show' command expects a pid number or a process name");
208        }
209        e if e.starts_with("kill ") => {
210            let tmp: Vec<&str> = e
211                .split(' ')
212                .map(|s| s.trim())
213                .filter(|s| !s.is_empty())
214                .collect();
215
216            if tmp.len() != 3 {
217                println!("kill command takes the pid and a signal number in parameter!");
218                println!("example: kill 1254 9");
219            } else {
220                let Ok(pid) = Pid::from_str(tmp[1]) else {
221                    eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
222                    return false;
223                };
224                let Ok(signal) = usize::from_str(tmp[2]) else {
225                    eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
226                    return false;
227                };
228                let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
229                    eprintln!(
230                        "No signal matching {signal}. Use the `signals` command to get the \
231                         list of signals.",
232                    );
233                    return false;
234                };
235
236                match sys.process(pid) {
237                    Some(p) => {
238                        if let Some(res) = p.kill_with(*signal) {
239                            println!("kill: {res}");
240                        } else {
241                            eprintln!("kill: signal not supported on this platform");
242                        }
243                    }
244                    None => {
245                        eprintln!("pid not found");
246                    }
247                }
248            }
249        }
250        "disks" => {
251            for disk in disks {
252                println!("{disk:?}");
253            }
254        }
255        "users" => {
256            for user in users {
257                println!("{:?} => {:?}", user.name(), user.groups(),);
258            }
259        }
260        "groups" => {
261            for group in Groups::new_with_refreshed_list().list() {
262                println!("{group:?}");
263            }
264        }
265        "boot_time" => {
266            println!("{} seconds", System::boot_time());
267        }
268        "uptime" => {
269            let up = System::uptime();
270            let mut uptime = up;
271            let days = uptime / 86400;
272            uptime -= days * 86400;
273            let hours = uptime / 3600;
274            uptime -= hours * 3600;
275            let minutes = uptime / 60;
276            println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
277        }
278        x if x.starts_with("refresh") => {
279            if x == "refresh" {
280                println!("Getting processes' information...");
281                sys.refresh_all();
282                println!("Done.");
283            } else if x.starts_with("refresh ") {
284                println!("Getting process' information...");
285                if let Some(pid) = x
286                    .split(' ')
287                    .filter_map(|pid| pid.parse().ok())
288                    .take(1)
289                    .next()
290                {
291                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
292                        println!("Process `{pid}` updated successfully");
293                    } else {
294                        println!("Process `{pid}` couldn't be updated...");
295                    }
296                } else {
297                    println!("Invalid [pid] received...");
298                }
299            } else {
300                println!(
301                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
302                     list.",
303                );
304            }
305        }
306        "pid" => {
307            println!(
308                "PID: {}",
309                sysinfo::get_current_pid().expect("failed to get PID")
310            );
311        }
312        "system" => {
313            println!(
314                "System name:              {}\n\
315                 System kernel version:    {}\n\
316                 System OS version:        {}\n\
317                 System OS (long) version: {}\n\
318                 System host name:         {}\n\
319                 System kernel:            {}",
320                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
321                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
322                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
323                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
324                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
325                System::kernel_long_version(),
326            );
327        }
328        e => {
329            println!(
330                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
331                 list.",
332            );
333        }
334    }
335    false
336}
Source

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());
}
Source

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());
}
Source

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());
}
Source

pub fn accumulated_cpu_time(&self) -> u64

Returns the total accumulated CPU usage (in CPU-milliseconds). Note that it might be bigger than the total clock run time of a process if run on a multi-core machine.

use sysinfo::{Pid, System};

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

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,
    );
}
Source

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());
}
Source

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());
}
Source

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());
}
Source

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());
}
Source

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());
}
Source

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());
            }
        }
    }
}
Source

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());
    }
}
Source

pub fn exists(&self) -> bool

Returns true if the process doesn’t exist anymore but was not yet removed from the processes list because the remove_dead_processes argument was set to false in methods like System::refresh_processes.

use sysinfo::{ProcessesToUpdate, System};

let mut s = System::new_all();
// We set the `remove_dead_processes` to `false`.
s.refresh_processes(ProcessesToUpdate::All, false);

for (_, process) in s.processes() {
    println!(
        "Process {:?} {}",
        process.pid(),
        if process.exists() { "exists" } else { "doesn't exist" },
    );
}
Source

pub fn open_files(&self) -> Option<usize>

Returns the number of open files in the current process.

Returns None if it failed retrieving the information or if the current system is not supported.

Important: this information is computed every time this function is called.

use sysinfo::System;

let s = System::new_all();

for (_, process) in s.processes() {
    println!(
        "Process {:?} {:?}",
        process.pid(),
        process.open_files(),
    );
}
Examples found in repository?
examples/simple.rs (line 169)
65fn interpret_input(
66    input: &str,
67    sys: &mut System,
68    networks: &mut Networks,
69    disks: &mut Disks,
70    components: &mut Components,
71    users: &mut Users,
72) -> bool {
73    match input.trim() {
74        "help" => print_help(),
75        "refresh_disks" => {
76            println!("Refreshing disk list...");
77            disks.refresh(true);
78            println!("Done.");
79        }
80        "refresh_users" => {
81            println!("Refreshing user list...");
82            users.refresh();
83            println!("Done.");
84        }
85        "refresh_networks" => {
86            println!("Refreshing network list...");
87            networks.refresh(true);
88            println!("Done.");
89        }
90        "refresh_components" => {
91            println!("Refreshing component list...");
92            components.refresh(true);
93            println!("Done.");
94        }
95        "refresh_cpu" => {
96            println!("Refreshing CPUs...");
97            sys.refresh_cpu_all();
98            println!("Done.");
99        }
100        "signals" => {
101            for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
102                println!("{:2}:{sig:?}", nb + 1);
103            }
104        }
105        "cpus" => {
106            // Note: you should refresh a few times before using this, so that usage statistics
107            // can be ascertained
108            println!(
109                "number of physical cores: {}",
110                System::physical_core_count()
111                    .map(|c| c.to_string())
112                    .unwrap_or_else(|| "Unknown".to_owned()),
113            );
114            println!("total CPU usage: {}%", sys.global_cpu_usage(),);
115            for cpu in sys.cpus() {
116                println!("{cpu:?}");
117            }
118        }
119        "memory" => {
120            println!("total memory:     {: >10} KB", sys.total_memory() / 1_000);
121            println!(
122                "available memory: {: >10} KB",
123                sys.available_memory() / 1_000
124            );
125            println!("used memory:      {: >10} KB", sys.used_memory() / 1_000);
126            println!("total swap:       {: >10} KB", sys.total_swap() / 1_000);
127            println!("used swap:        {: >10} KB", sys.used_swap() / 1_000);
128        }
129        "quit" | "exit" => return true,
130        "all" => {
131            for (pid, proc_) in sys.processes() {
132                println!(
133                    "{}:{} status={:?}",
134                    pid,
135                    proc_.name().to_string_lossy(),
136                    proc_.status()
137                );
138            }
139        }
140        "frequency" => {
141            for cpu in sys.cpus() {
142                println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
143            }
144        }
145        "vendor_id" => {
146            println!("vendor ID: {}", sys.cpus()[0].vendor_id());
147        }
148        "brand" => {
149            println!("brand: {}", sys.cpus()[0].brand());
150        }
151        "load_avg" => {
152            let load_avg = System::load_average();
153            println!("one minute     : {}%", load_avg.one);
154            println!("five minutes   : {}%", load_avg.five);
155            println!("fifteen minutes: {}%", load_avg.fifteen);
156        }
157        e if e.starts_with("show ") => {
158            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
159
160            if tmp.len() != 2 {
161                println!("show command takes a pid or a name in parameter!");
162                println!("example: show 1254");
163            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
164                match sys.process(pid) {
165                    Some(p) => {
166                        println!("{:?}", *p);
167                        println!(
168                            "Files open/limit: {:?}/{:?}",
169                            p.open_files(),
170                            p.open_files_limit(),
171                        );
172                    }
173                    None => {
174                        println!("pid \"{pid:?}\" not found");
175                    }
176                }
177            } else {
178                let proc_name = tmp[1];
179                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
180                    println!("==== {} ====", proc_.name().to_string_lossy());
181                    println!("{proc_:?}");
182                }
183            }
184        }
185        "temperature" => {
186            for component in components.iter() {
187                println!("{component:?}");
188            }
189        }
190        "network" => {
191            for (interface_name, data) in networks.iter() {
192                println!(
193                    "\
194{interface_name}:
195  ether {}
196  input data  (new / total): {} / {} B
197  output data (new / total): {} / {} B",
198                    data.mac_address(),
199                    data.received(),
200                    data.total_received(),
201                    data.transmitted(),
202                    data.total_transmitted(),
203                );
204            }
205        }
206        "show" => {
207            println!("'show' command expects a pid number or a process name");
208        }
209        e if e.starts_with("kill ") => {
210            let tmp: Vec<&str> = e
211                .split(' ')
212                .map(|s| s.trim())
213                .filter(|s| !s.is_empty())
214                .collect();
215
216            if tmp.len() != 3 {
217                println!("kill command takes the pid and a signal number in parameter!");
218                println!("example: kill 1254 9");
219            } else {
220                let Ok(pid) = Pid::from_str(tmp[1]) else {
221                    eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
222                    return false;
223                };
224                let Ok(signal) = usize::from_str(tmp[2]) else {
225                    eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
226                    return false;
227                };
228                let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
229                    eprintln!(
230                        "No signal matching {signal}. Use the `signals` command to get the \
231                         list of signals.",
232                    );
233                    return false;
234                };
235
236                match sys.process(pid) {
237                    Some(p) => {
238                        if let Some(res) = p.kill_with(*signal) {
239                            println!("kill: {res}");
240                        } else {
241                            eprintln!("kill: signal not supported on this platform");
242                        }
243                    }
244                    None => {
245                        eprintln!("pid not found");
246                    }
247                }
248            }
249        }
250        "disks" => {
251            for disk in disks {
252                println!("{disk:?}");
253            }
254        }
255        "users" => {
256            for user in users {
257                println!("{:?} => {:?}", user.name(), user.groups(),);
258            }
259        }
260        "groups" => {
261            for group in Groups::new_with_refreshed_list().list() {
262                println!("{group:?}");
263            }
264        }
265        "boot_time" => {
266            println!("{} seconds", System::boot_time());
267        }
268        "uptime" => {
269            let up = System::uptime();
270            let mut uptime = up;
271            let days = uptime / 86400;
272            uptime -= days * 86400;
273            let hours = uptime / 3600;
274            uptime -= hours * 3600;
275            let minutes = uptime / 60;
276            println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
277        }
278        x if x.starts_with("refresh") => {
279            if x == "refresh" {
280                println!("Getting processes' information...");
281                sys.refresh_all();
282                println!("Done.");
283            } else if x.starts_with("refresh ") {
284                println!("Getting process' information...");
285                if let Some(pid) = x
286                    .split(' ')
287                    .filter_map(|pid| pid.parse().ok())
288                    .take(1)
289                    .next()
290                {
291                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
292                        println!("Process `{pid}` updated successfully");
293                    } else {
294                        println!("Process `{pid}` couldn't be updated...");
295                    }
296                } else {
297                    println!("Invalid [pid] received...");
298                }
299            } else {
300                println!(
301                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
302                     list.",
303                );
304            }
305        }
306        "pid" => {
307            println!(
308                "PID: {}",
309                sysinfo::get_current_pid().expect("failed to get PID")
310            );
311        }
312        "system" => {
313            println!(
314                "System name:              {}\n\
315                 System kernel version:    {}\n\
316                 System OS version:        {}\n\
317                 System OS (long) version: {}\n\
318                 System host name:         {}\n\
319                 System kernel:            {}",
320                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
321                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
322                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
323                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
324                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
325                System::kernel_long_version(),
326            );
327        }
328        e => {
329            println!(
330                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
331                 list.",
332            );
333        }
334    }
335    false
336}
Source

pub fn open_files_limit(&self) -> Option<usize>

Returns the maximum number of open files for the current process.

Returns None if it failed retrieving the information or if the current system is not supported.

Important: this information is computed every time this function is called.

use sysinfo::System;

let s = System::new_all();

for (_, process) in s.processes() {
    println!(
        "Process {:?} {:?}",
        process.pid(),
        process.open_files_limit(),
    );
}
Examples found in repository?
examples/simple.rs (line 170)
65fn interpret_input(
66    input: &str,
67    sys: &mut System,
68    networks: &mut Networks,
69    disks: &mut Disks,
70    components: &mut Components,
71    users: &mut Users,
72) -> bool {
73    match input.trim() {
74        "help" => print_help(),
75        "refresh_disks" => {
76            println!("Refreshing disk list...");
77            disks.refresh(true);
78            println!("Done.");
79        }
80        "refresh_users" => {
81            println!("Refreshing user list...");
82            users.refresh();
83            println!("Done.");
84        }
85        "refresh_networks" => {
86            println!("Refreshing network list...");
87            networks.refresh(true);
88            println!("Done.");
89        }
90        "refresh_components" => {
91            println!("Refreshing component list...");
92            components.refresh(true);
93            println!("Done.");
94        }
95        "refresh_cpu" => {
96            println!("Refreshing CPUs...");
97            sys.refresh_cpu_all();
98            println!("Done.");
99        }
100        "signals" => {
101            for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
102                println!("{:2}:{sig:?}", nb + 1);
103            }
104        }
105        "cpus" => {
106            // Note: you should refresh a few times before using this, so that usage statistics
107            // can be ascertained
108            println!(
109                "number of physical cores: {}",
110                System::physical_core_count()
111                    .map(|c| c.to_string())
112                    .unwrap_or_else(|| "Unknown".to_owned()),
113            );
114            println!("total CPU usage: {}%", sys.global_cpu_usage(),);
115            for cpu in sys.cpus() {
116                println!("{cpu:?}");
117            }
118        }
119        "memory" => {
120            println!("total memory:     {: >10} KB", sys.total_memory() / 1_000);
121            println!(
122                "available memory: {: >10} KB",
123                sys.available_memory() / 1_000
124            );
125            println!("used memory:      {: >10} KB", sys.used_memory() / 1_000);
126            println!("total swap:       {: >10} KB", sys.total_swap() / 1_000);
127            println!("used swap:        {: >10} KB", sys.used_swap() / 1_000);
128        }
129        "quit" | "exit" => return true,
130        "all" => {
131            for (pid, proc_) in sys.processes() {
132                println!(
133                    "{}:{} status={:?}",
134                    pid,
135                    proc_.name().to_string_lossy(),
136                    proc_.status()
137                );
138            }
139        }
140        "frequency" => {
141            for cpu in sys.cpus() {
142                println!("[{}] {} MHz", cpu.name(), cpu.frequency(),);
143            }
144        }
145        "vendor_id" => {
146            println!("vendor ID: {}", sys.cpus()[0].vendor_id());
147        }
148        "brand" => {
149            println!("brand: {}", sys.cpus()[0].brand());
150        }
151        "load_avg" => {
152            let load_avg = System::load_average();
153            println!("one minute     : {}%", load_avg.one);
154            println!("five minutes   : {}%", load_avg.five);
155            println!("fifteen minutes: {}%", load_avg.fifteen);
156        }
157        e if e.starts_with("show ") => {
158            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
159
160            if tmp.len() != 2 {
161                println!("show command takes a pid or a name in parameter!");
162                println!("example: show 1254");
163            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
164                match sys.process(pid) {
165                    Some(p) => {
166                        println!("{:?}", *p);
167                        println!(
168                            "Files open/limit: {:?}/{:?}",
169                            p.open_files(),
170                            p.open_files_limit(),
171                        );
172                    }
173                    None => {
174                        println!("pid \"{pid:?}\" not found");
175                    }
176                }
177            } else {
178                let proc_name = tmp[1];
179                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
180                    println!("==== {} ====", proc_.name().to_string_lossy());
181                    println!("{proc_:?}");
182                }
183            }
184        }
185        "temperature" => {
186            for component in components.iter() {
187                println!("{component:?}");
188            }
189        }
190        "network" => {
191            for (interface_name, data) in networks.iter() {
192                println!(
193                    "\
194{interface_name}:
195  ether {}
196  input data  (new / total): {} / {} B
197  output data (new / total): {} / {} B",
198                    data.mac_address(),
199                    data.received(),
200                    data.total_received(),
201                    data.transmitted(),
202                    data.total_transmitted(),
203                );
204            }
205        }
206        "show" => {
207            println!("'show' command expects a pid number or a process name");
208        }
209        e if e.starts_with("kill ") => {
210            let tmp: Vec<&str> = e
211                .split(' ')
212                .map(|s| s.trim())
213                .filter(|s| !s.is_empty())
214                .collect();
215
216            if tmp.len() != 3 {
217                println!("kill command takes the pid and a signal number in parameter!");
218                println!("example: kill 1254 9");
219            } else {
220                let Ok(pid) = Pid::from_str(tmp[1]) else {
221                    eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
222                    return false;
223                };
224                let Ok(signal) = usize::from_str(tmp[2]) else {
225                    eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
226                    return false;
227                };
228                let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
229                    eprintln!(
230                        "No signal matching {signal}. Use the `signals` command to get the \
231                         list of signals.",
232                    );
233                    return false;
234                };
235
236                match sys.process(pid) {
237                    Some(p) => {
238                        if let Some(res) = p.kill_with(*signal) {
239                            println!("kill: {res}");
240                        } else {
241                            eprintln!("kill: signal not supported on this platform");
242                        }
243                    }
244                    None => {
245                        eprintln!("pid not found");
246                    }
247                }
248            }
249        }
250        "disks" => {
251            for disk in disks {
252                println!("{disk:?}");
253            }
254        }
255        "users" => {
256            for user in users {
257                println!("{:?} => {:?}", user.name(), user.groups(),);
258            }
259        }
260        "groups" => {
261            for group in Groups::new_with_refreshed_list().list() {
262                println!("{group:?}");
263            }
264        }
265        "boot_time" => {
266            println!("{} seconds", System::boot_time());
267        }
268        "uptime" => {
269            let up = System::uptime();
270            let mut uptime = up;
271            let days = uptime / 86400;
272            uptime -= days * 86400;
273            let hours = uptime / 3600;
274            uptime -= hours * 3600;
275            let minutes = uptime / 60;
276            println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)",);
277        }
278        x if x.starts_with("refresh") => {
279            if x == "refresh" {
280                println!("Getting processes' information...");
281                sys.refresh_all();
282                println!("Done.");
283            } else if x.starts_with("refresh ") {
284                println!("Getting process' information...");
285                if let Some(pid) = x
286                    .split(' ')
287                    .filter_map(|pid| pid.parse().ok())
288                    .take(1)
289                    .next()
290                {
291                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
292                        println!("Process `{pid}` updated successfully");
293                    } else {
294                        println!("Process `{pid}` couldn't be updated...");
295                    }
296                } else {
297                    println!("Invalid [pid] received...");
298                }
299            } else {
300                println!(
301                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
302                     list.",
303                );
304            }
305        }
306        "pid" => {
307            println!(
308                "PID: {}",
309                sysinfo::get_current_pid().expect("failed to get PID")
310            );
311        }
312        "system" => {
313            println!(
314                "System name:              {}\n\
315                 System kernel version:    {}\n\
316                 System OS version:        {}\n\
317                 System OS (long) version: {}\n\
318                 System host name:         {}\n\
319                 System kernel:            {}",
320                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
321                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
322                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
323                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
324                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
325                System::kernel_long_version(),
326            );
327        }
328        e => {
329            println!(
330                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
331                 list.",
332            );
333        }
334    }
335    false
336}

Trait Implementations§

Source§

impl Debug for Process

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Serialize for Process

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for Process

§

impl RefUnwindSafe for Process

§

impl Send for Process

§

impl Sync for Process

§

impl Unpin for Process

§

impl UnwindSafe for Process

Blanket Implementations§

§

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

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

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

§

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

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

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

§

fn into(self) -> U

Calls U::from(self).

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

§

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

§

type Error = Infallible

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

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

Performs the conversion.
§

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

§

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

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

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

Performs the conversion.