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.

⚠️ 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.

⚠️ 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 361)
150fn interpret_input(
151    input: &str,
152    sys: &mut System,
153    networks: &mut Networks,
154    disks: &mut Disks,
155    components: &mut Components,
156    users: &mut Users,
157) -> bool {
158    match input.trim() {
159        "help" => print_help(),
160        "refresh_disks" => {
161            writeln!(&mut io::stdout(), "Refreshing disk list...");
162            disks.refresh(true);
163            writeln!(&mut io::stdout(), "Done.");
164        }
165        "refresh_users" => {
166            writeln!(&mut io::stdout(), "Refreshing user list...");
167            users.refresh();
168            writeln!(&mut io::stdout(), "Done.");
169        }
170        "refresh_networks" => {
171            writeln!(&mut io::stdout(), "Refreshing network list...");
172            networks.refresh(true);
173            writeln!(&mut io::stdout(), "Done.");
174        }
175        "refresh_components" => {
176            writeln!(&mut io::stdout(), "Refreshing component list...");
177            components.refresh(true);
178            writeln!(&mut io::stdout(), "Done.");
179        }
180        "refresh_cpu" => {
181            writeln!(&mut io::stdout(), "Refreshing CPUs...");
182            sys.refresh_cpu_all();
183            writeln!(&mut io::stdout(), "Done.");
184        }
185        "signals" => {
186            let mut nb = 1i32;
187
188            for sig in signals {
189                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
190                nb += 1;
191            }
192        }
193        "cpus" => {
194            // Note: you should refresh a few times before using this, so that usage statistics
195            // can be ascertained
196            writeln!(
197                &mut io::stdout(),
198                "number of physical cores: {}",
199                System::physical_core_count()
200                    .map(|c| c.to_string())
201                    .unwrap_or_else(|| "Unknown".to_owned()),
202            );
203            writeln!(
204                &mut io::stdout(),
205                "total CPU usage: {}%",
206                sys.global_cpu_usage(),
207            );
208            for cpu in sys.cpus() {
209                writeln!(&mut io::stdout(), "{cpu:?}");
210            }
211        }
212        "memory" => {
213            writeln!(
214                &mut io::stdout(),
215                "total memory:     {: >10} KB",
216                sys.total_memory() / 1_000
217            );
218            writeln!(
219                &mut io::stdout(),
220                "available memory: {: >10} KB",
221                sys.available_memory() / 1_000
222            );
223            writeln!(
224                &mut io::stdout(),
225                "used memory:      {: >10} KB",
226                sys.used_memory() / 1_000
227            );
228            writeln!(
229                &mut io::stdout(),
230                "total swap:       {: >10} KB",
231                sys.total_swap() / 1_000
232            );
233            writeln!(
234                &mut io::stdout(),
235                "used swap:        {: >10} KB",
236                sys.used_swap() / 1_000
237            );
238        }
239        "quit" | "exit" => return true,
240        "all" => {
241            for (pid, proc_) in sys.processes() {
242                writeln!(
243                    &mut io::stdout(),
244                    "{}:{} status={:?}",
245                    pid,
246                    proc_.name().to_string_lossy(),
247                    proc_.status()
248                );
249            }
250        }
251        "frequency" => {
252            for cpu in sys.cpus() {
253                writeln!(
254                    &mut io::stdout(),
255                    "[{}] {} MHz",
256                    cpu.name(),
257                    cpu.frequency(),
258                );
259            }
260        }
261        "vendor_id" => {
262            writeln!(
263                &mut io::stdout(),
264                "vendor ID: {}",
265                sys.cpus()[0].vendor_id()
266            );
267        }
268        "brand" => {
269            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
270        }
271        "load_avg" => {
272            let load_avg = System::load_average();
273            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
274            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
275            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
276        }
277        e if e.starts_with("show ") => {
278            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
279
280            if tmp.len() != 2 {
281                writeln!(
282                    &mut io::stdout(),
283                    "show command takes a pid or a name in parameter!"
284                );
285                writeln!(&mut io::stdout(), "example: show 1254");
286            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
287                match sys.process(pid) {
288                    Some(p) => {
289                        writeln!(&mut io::stdout(), "{:?}", *p);
290                        writeln!(
291                            &mut io::stdout(),
292                            "Files open/limit: {:?}/{:?}",
293                            p.open_files(),
294                            p.open_files_limit(),
295                        );
296                    }
297                    None => {
298                        writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found");
299                    }
300                }
301            } else {
302                let proc_name = tmp[1];
303                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
304                    writeln!(
305                        &mut io::stdout(),
306                        "==== {} ====",
307                        proc_.name().to_string_lossy()
308                    );
309                    writeln!(&mut io::stdout(), "{proc_:?}");
310                }
311            }
312        }
313        "temperature" => {
314            for component in components.iter() {
315                writeln!(&mut io::stdout(), "{component:?}");
316            }
317        }
318        "network" => {
319            for (interface_name, data) in networks.iter() {
320                writeln!(
321                    &mut io::stdout(),
322                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
323                    interface_name,
324                    data.mac_address(),
325                    data.received(),
326                    data.total_received(),
327                    data.transmitted(),
328                    data.total_transmitted(),
329                );
330            }
331        }
332        "show" => {
333            writeln!(
334                &mut io::stdout(),
335                "'show' command expects a pid number or a process name"
336            );
337        }
338        e if e.starts_with("kill ") => {
339            let tmp: Vec<&str> = e.split(' ').collect();
340
341            if tmp.len() != 3 {
342                writeln!(
343                    &mut io::stdout(),
344                    "kill command takes the pid and a signal number in parameter!"
345                );
346                writeln!(&mut io::stdout(), "example: kill 1254 9");
347            } else {
348                let pid = Pid::from_str(tmp[1]).unwrap();
349                let signal = i32::from_str(tmp[2]).unwrap();
350
351                if signal < 1 || signal > 31 {
352                    writeln!(
353                        &mut io::stdout(),
354                        "Signal must be between 0 and 32 ! See the signals list with the \
355                         signals command"
356                    );
357                } else {
358                    match sys.process(pid) {
359                        Some(p) => {
360                            if let Some(res) =
361                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
362                            {
363                                writeln!(&mut io::stdout(), "kill: {res}");
364                            } else {
365                                writeln!(
366                                    &mut io::stdout(),
367                                    "kill: signal not supported on this platform"
368                                );
369                            }
370                        }
371                        None => {
372                            writeln!(&mut io::stdout(), "pid not found");
373                        }
374                    };
375                }
376            }
377        }
378        "disks" => {
379            for disk in disks {
380                writeln!(&mut io::stdout(), "{disk:?}");
381            }
382        }
383        "users" => {
384            for user in users {
385                writeln!(
386                    &mut io::stdout(),
387                    "{:?} => {:?}",
388                    user.name(),
389                    user.groups()
390                );
391            }
392        }
393        "boot_time" => {
394            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
395        }
396        "uptime" => {
397            let up = System::uptime();
398            let mut uptime = up;
399            let days = uptime / 86400;
400            uptime -= days * 86400;
401            let hours = uptime / 3600;
402            uptime -= hours * 3600;
403            let minutes = uptime / 60;
404            writeln!(
405                &mut io::stdout(),
406                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
407            );
408        }
409        x if x.starts_with("refresh") => {
410            if x == "refresh" {
411                writeln!(&mut io::stdout(), "Getting processes' information...");
412                sys.refresh_all();
413                writeln!(&mut io::stdout(), "Done.");
414            } else if x.starts_with("refresh ") {
415                writeln!(&mut io::stdout(), "Getting process' information...");
416                if let Some(pid) = x
417                    .split(' ')
418                    .filter_map(|pid| pid.parse().ok())
419                    .take(1)
420                    .next()
421                {
422                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
423                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
424                    } else {
425                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
426                    }
427                } else {
428                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
429                }
430            } else {
431                writeln!(
432                    &mut io::stdout(),
433                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
434                     list.",
435                );
436            }
437        }
438        "pid" => {
439            writeln!(
440                &mut io::stdout(),
441                "PID: {}",
442                sysinfo::get_current_pid().expect("failed to get PID")
443            );
444        }
445        "system" => {
446            writeln!(
447                &mut io::stdout(),
448                "System name:              {}\n\
449                 System kernel version:    {}\n\
450                 System OS version:        {}\n\
451                 System OS (long) version: {}\n\
452                 System host name:         {}\n\
453		 System kernel:            {}",
454                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
455                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
456                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
457                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
458                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
459                System::kernel_long_version(),
460            );
461        }
462        e => {
463            writeln!(
464                &mut io::stdout(),
465                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
466                 list.",
467            );
468        }
469    }
470    false
471}
Source

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

Wait for process termination and returns its [ExitStatus] if it could be retrieved, returns None otherwise.

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 246)
150fn interpret_input(
151    input: &str,
152    sys: &mut System,
153    networks: &mut Networks,
154    disks: &mut Disks,
155    components: &mut Components,
156    users: &mut Users,
157) -> bool {
158    match input.trim() {
159        "help" => print_help(),
160        "refresh_disks" => {
161            writeln!(&mut io::stdout(), "Refreshing disk list...");
162            disks.refresh(true);
163            writeln!(&mut io::stdout(), "Done.");
164        }
165        "refresh_users" => {
166            writeln!(&mut io::stdout(), "Refreshing user list...");
167            users.refresh();
168            writeln!(&mut io::stdout(), "Done.");
169        }
170        "refresh_networks" => {
171            writeln!(&mut io::stdout(), "Refreshing network list...");
172            networks.refresh(true);
173            writeln!(&mut io::stdout(), "Done.");
174        }
175        "refresh_components" => {
176            writeln!(&mut io::stdout(), "Refreshing component list...");
177            components.refresh(true);
178            writeln!(&mut io::stdout(), "Done.");
179        }
180        "refresh_cpu" => {
181            writeln!(&mut io::stdout(), "Refreshing CPUs...");
182            sys.refresh_cpu_all();
183            writeln!(&mut io::stdout(), "Done.");
184        }
185        "signals" => {
186            let mut nb = 1i32;
187
188            for sig in signals {
189                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
190                nb += 1;
191            }
192        }
193        "cpus" => {
194            // Note: you should refresh a few times before using this, so that usage statistics
195            // can be ascertained
196            writeln!(
197                &mut io::stdout(),
198                "number of physical cores: {}",
199                System::physical_core_count()
200                    .map(|c| c.to_string())
201                    .unwrap_or_else(|| "Unknown".to_owned()),
202            );
203            writeln!(
204                &mut io::stdout(),
205                "total CPU usage: {}%",
206                sys.global_cpu_usage(),
207            );
208            for cpu in sys.cpus() {
209                writeln!(&mut io::stdout(), "{cpu:?}");
210            }
211        }
212        "memory" => {
213            writeln!(
214                &mut io::stdout(),
215                "total memory:     {: >10} KB",
216                sys.total_memory() / 1_000
217            );
218            writeln!(
219                &mut io::stdout(),
220                "available memory: {: >10} KB",
221                sys.available_memory() / 1_000
222            );
223            writeln!(
224                &mut io::stdout(),
225                "used memory:      {: >10} KB",
226                sys.used_memory() / 1_000
227            );
228            writeln!(
229                &mut io::stdout(),
230                "total swap:       {: >10} KB",
231                sys.total_swap() / 1_000
232            );
233            writeln!(
234                &mut io::stdout(),
235                "used swap:        {: >10} KB",
236                sys.used_swap() / 1_000
237            );
238        }
239        "quit" | "exit" => return true,
240        "all" => {
241            for (pid, proc_) in sys.processes() {
242                writeln!(
243                    &mut io::stdout(),
244                    "{}:{} status={:?}",
245                    pid,
246                    proc_.name().to_string_lossy(),
247                    proc_.status()
248                );
249            }
250        }
251        "frequency" => {
252            for cpu in sys.cpus() {
253                writeln!(
254                    &mut io::stdout(),
255                    "[{}] {} MHz",
256                    cpu.name(),
257                    cpu.frequency(),
258                );
259            }
260        }
261        "vendor_id" => {
262            writeln!(
263                &mut io::stdout(),
264                "vendor ID: {}",
265                sys.cpus()[0].vendor_id()
266            );
267        }
268        "brand" => {
269            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
270        }
271        "load_avg" => {
272            let load_avg = System::load_average();
273            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
274            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
275            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
276        }
277        e if e.starts_with("show ") => {
278            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
279
280            if tmp.len() != 2 {
281                writeln!(
282                    &mut io::stdout(),
283                    "show command takes a pid or a name in parameter!"
284                );
285                writeln!(&mut io::stdout(), "example: show 1254");
286            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
287                match sys.process(pid) {
288                    Some(p) => {
289                        writeln!(&mut io::stdout(), "{:?}", *p);
290                        writeln!(
291                            &mut io::stdout(),
292                            "Files open/limit: {:?}/{:?}",
293                            p.open_files(),
294                            p.open_files_limit(),
295                        );
296                    }
297                    None => {
298                        writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found");
299                    }
300                }
301            } else {
302                let proc_name = tmp[1];
303                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
304                    writeln!(
305                        &mut io::stdout(),
306                        "==== {} ====",
307                        proc_.name().to_string_lossy()
308                    );
309                    writeln!(&mut io::stdout(), "{proc_:?}");
310                }
311            }
312        }
313        "temperature" => {
314            for component in components.iter() {
315                writeln!(&mut io::stdout(), "{component:?}");
316            }
317        }
318        "network" => {
319            for (interface_name, data) in networks.iter() {
320                writeln!(
321                    &mut io::stdout(),
322                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
323                    interface_name,
324                    data.mac_address(),
325                    data.received(),
326                    data.total_received(),
327                    data.transmitted(),
328                    data.total_transmitted(),
329                );
330            }
331        }
332        "show" => {
333            writeln!(
334                &mut io::stdout(),
335                "'show' command expects a pid number or a process name"
336            );
337        }
338        e if e.starts_with("kill ") => {
339            let tmp: Vec<&str> = e.split(' ').collect();
340
341            if tmp.len() != 3 {
342                writeln!(
343                    &mut io::stdout(),
344                    "kill command takes the pid and a signal number in parameter!"
345                );
346                writeln!(&mut io::stdout(), "example: kill 1254 9");
347            } else {
348                let pid = Pid::from_str(tmp[1]).unwrap();
349                let signal = i32::from_str(tmp[2]).unwrap();
350
351                if signal < 1 || signal > 31 {
352                    writeln!(
353                        &mut io::stdout(),
354                        "Signal must be between 0 and 32 ! See the signals list with the \
355                         signals command"
356                    );
357                } else {
358                    match sys.process(pid) {
359                        Some(p) => {
360                            if let Some(res) =
361                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
362                            {
363                                writeln!(&mut io::stdout(), "kill: {res}");
364                            } else {
365                                writeln!(
366                                    &mut io::stdout(),
367                                    "kill: signal not supported on this platform"
368                                );
369                            }
370                        }
371                        None => {
372                            writeln!(&mut io::stdout(), "pid not found");
373                        }
374                    };
375                }
376            }
377        }
378        "disks" => {
379            for disk in disks {
380                writeln!(&mut io::stdout(), "{disk:?}");
381            }
382        }
383        "users" => {
384            for user in users {
385                writeln!(
386                    &mut io::stdout(),
387                    "{:?} => {:?}",
388                    user.name(),
389                    user.groups()
390                );
391            }
392        }
393        "boot_time" => {
394            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
395        }
396        "uptime" => {
397            let up = System::uptime();
398            let mut uptime = up;
399            let days = uptime / 86400;
400            uptime -= days * 86400;
401            let hours = uptime / 3600;
402            uptime -= hours * 3600;
403            let minutes = uptime / 60;
404            writeln!(
405                &mut io::stdout(),
406                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
407            );
408        }
409        x if x.starts_with("refresh") => {
410            if x == "refresh" {
411                writeln!(&mut io::stdout(), "Getting processes' information...");
412                sys.refresh_all();
413                writeln!(&mut io::stdout(), "Done.");
414            } else if x.starts_with("refresh ") {
415                writeln!(&mut io::stdout(), "Getting process' information...");
416                if let Some(pid) = x
417                    .split(' ')
418                    .filter_map(|pid| pid.parse().ok())
419                    .take(1)
420                    .next()
421                {
422                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
423                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
424                    } else {
425                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
426                    }
427                } else {
428                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
429                }
430            } else {
431                writeln!(
432                    &mut io::stdout(),
433                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
434                     list.",
435                );
436            }
437        }
438        "pid" => {
439            writeln!(
440                &mut io::stdout(),
441                "PID: {}",
442                sysinfo::get_current_pid().expect("failed to get PID")
443            );
444        }
445        "system" => {
446            writeln!(
447                &mut io::stdout(),
448                "System name:              {}\n\
449                 System kernel version:    {}\n\
450                 System OS version:        {}\n\
451                 System OS (long) version: {}\n\
452                 System host name:         {}\n\
453		 System kernel:            {}",
454                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
455                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
456                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
457                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
458                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
459                System::kernel_long_version(),
460            );
461        }
462        e => {
463            writeln!(
464                &mut io::stdout(),
465                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
466                 list.",
467            );
468        }
469    }
470    false
471}
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 247)
150fn interpret_input(
151    input: &str,
152    sys: &mut System,
153    networks: &mut Networks,
154    disks: &mut Disks,
155    components: &mut Components,
156    users: &mut Users,
157) -> bool {
158    match input.trim() {
159        "help" => print_help(),
160        "refresh_disks" => {
161            writeln!(&mut io::stdout(), "Refreshing disk list...");
162            disks.refresh(true);
163            writeln!(&mut io::stdout(), "Done.");
164        }
165        "refresh_users" => {
166            writeln!(&mut io::stdout(), "Refreshing user list...");
167            users.refresh();
168            writeln!(&mut io::stdout(), "Done.");
169        }
170        "refresh_networks" => {
171            writeln!(&mut io::stdout(), "Refreshing network list...");
172            networks.refresh(true);
173            writeln!(&mut io::stdout(), "Done.");
174        }
175        "refresh_components" => {
176            writeln!(&mut io::stdout(), "Refreshing component list...");
177            components.refresh(true);
178            writeln!(&mut io::stdout(), "Done.");
179        }
180        "refresh_cpu" => {
181            writeln!(&mut io::stdout(), "Refreshing CPUs...");
182            sys.refresh_cpu_all();
183            writeln!(&mut io::stdout(), "Done.");
184        }
185        "signals" => {
186            let mut nb = 1i32;
187
188            for sig in signals {
189                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
190                nb += 1;
191            }
192        }
193        "cpus" => {
194            // Note: you should refresh a few times before using this, so that usage statistics
195            // can be ascertained
196            writeln!(
197                &mut io::stdout(),
198                "number of physical cores: {}",
199                System::physical_core_count()
200                    .map(|c| c.to_string())
201                    .unwrap_or_else(|| "Unknown".to_owned()),
202            );
203            writeln!(
204                &mut io::stdout(),
205                "total CPU usage: {}%",
206                sys.global_cpu_usage(),
207            );
208            for cpu in sys.cpus() {
209                writeln!(&mut io::stdout(), "{cpu:?}");
210            }
211        }
212        "memory" => {
213            writeln!(
214                &mut io::stdout(),
215                "total memory:     {: >10} KB",
216                sys.total_memory() / 1_000
217            );
218            writeln!(
219                &mut io::stdout(),
220                "available memory: {: >10} KB",
221                sys.available_memory() / 1_000
222            );
223            writeln!(
224                &mut io::stdout(),
225                "used memory:      {: >10} KB",
226                sys.used_memory() / 1_000
227            );
228            writeln!(
229                &mut io::stdout(),
230                "total swap:       {: >10} KB",
231                sys.total_swap() / 1_000
232            );
233            writeln!(
234                &mut io::stdout(),
235                "used swap:        {: >10} KB",
236                sys.used_swap() / 1_000
237            );
238        }
239        "quit" | "exit" => return true,
240        "all" => {
241            for (pid, proc_) in sys.processes() {
242                writeln!(
243                    &mut io::stdout(),
244                    "{}:{} status={:?}",
245                    pid,
246                    proc_.name().to_string_lossy(),
247                    proc_.status()
248                );
249            }
250        }
251        "frequency" => {
252            for cpu in sys.cpus() {
253                writeln!(
254                    &mut io::stdout(),
255                    "[{}] {} MHz",
256                    cpu.name(),
257                    cpu.frequency(),
258                );
259            }
260        }
261        "vendor_id" => {
262            writeln!(
263                &mut io::stdout(),
264                "vendor ID: {}",
265                sys.cpus()[0].vendor_id()
266            );
267        }
268        "brand" => {
269            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
270        }
271        "load_avg" => {
272            let load_avg = System::load_average();
273            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
274            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
275            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
276        }
277        e if e.starts_with("show ") => {
278            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
279
280            if tmp.len() != 2 {
281                writeln!(
282                    &mut io::stdout(),
283                    "show command takes a pid or a name in parameter!"
284                );
285                writeln!(&mut io::stdout(), "example: show 1254");
286            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
287                match sys.process(pid) {
288                    Some(p) => {
289                        writeln!(&mut io::stdout(), "{:?}", *p);
290                        writeln!(
291                            &mut io::stdout(),
292                            "Files open/limit: {:?}/{:?}",
293                            p.open_files(),
294                            p.open_files_limit(),
295                        );
296                    }
297                    None => {
298                        writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found");
299                    }
300                }
301            } else {
302                let proc_name = tmp[1];
303                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
304                    writeln!(
305                        &mut io::stdout(),
306                        "==== {} ====",
307                        proc_.name().to_string_lossy()
308                    );
309                    writeln!(&mut io::stdout(), "{proc_:?}");
310                }
311            }
312        }
313        "temperature" => {
314            for component in components.iter() {
315                writeln!(&mut io::stdout(), "{component:?}");
316            }
317        }
318        "network" => {
319            for (interface_name, data) in networks.iter() {
320                writeln!(
321                    &mut io::stdout(),
322                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
323                    interface_name,
324                    data.mac_address(),
325                    data.received(),
326                    data.total_received(),
327                    data.transmitted(),
328                    data.total_transmitted(),
329                );
330            }
331        }
332        "show" => {
333            writeln!(
334                &mut io::stdout(),
335                "'show' command expects a pid number or a process name"
336            );
337        }
338        e if e.starts_with("kill ") => {
339            let tmp: Vec<&str> = e.split(' ').collect();
340
341            if tmp.len() != 3 {
342                writeln!(
343                    &mut io::stdout(),
344                    "kill command takes the pid and a signal number in parameter!"
345                );
346                writeln!(&mut io::stdout(), "example: kill 1254 9");
347            } else {
348                let pid = Pid::from_str(tmp[1]).unwrap();
349                let signal = i32::from_str(tmp[2]).unwrap();
350
351                if signal < 1 || signal > 31 {
352                    writeln!(
353                        &mut io::stdout(),
354                        "Signal must be between 0 and 32 ! See the signals list with the \
355                         signals command"
356                    );
357                } else {
358                    match sys.process(pid) {
359                        Some(p) => {
360                            if let Some(res) =
361                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
362                            {
363                                writeln!(&mut io::stdout(), "kill: {res}");
364                            } else {
365                                writeln!(
366                                    &mut io::stdout(),
367                                    "kill: signal not supported on this platform"
368                                );
369                            }
370                        }
371                        None => {
372                            writeln!(&mut io::stdout(), "pid not found");
373                        }
374                    };
375                }
376            }
377        }
378        "disks" => {
379            for disk in disks {
380                writeln!(&mut io::stdout(), "{disk:?}");
381            }
382        }
383        "users" => {
384            for user in users {
385                writeln!(
386                    &mut io::stdout(),
387                    "{:?} => {:?}",
388                    user.name(),
389                    user.groups()
390                );
391            }
392        }
393        "boot_time" => {
394            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
395        }
396        "uptime" => {
397            let up = System::uptime();
398            let mut uptime = up;
399            let days = uptime / 86400;
400            uptime -= days * 86400;
401            let hours = uptime / 3600;
402            uptime -= hours * 3600;
403            let minutes = uptime / 60;
404            writeln!(
405                &mut io::stdout(),
406                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
407            );
408        }
409        x if x.starts_with("refresh") => {
410            if x == "refresh" {
411                writeln!(&mut io::stdout(), "Getting processes' information...");
412                sys.refresh_all();
413                writeln!(&mut io::stdout(), "Done.");
414            } else if x.starts_with("refresh ") {
415                writeln!(&mut io::stdout(), "Getting process' information...");
416                if let Some(pid) = x
417                    .split(' ')
418                    .filter_map(|pid| pid.parse().ok())
419                    .take(1)
420                    .next()
421                {
422                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
423                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
424                    } else {
425                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
426                    }
427                } else {
428                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
429                }
430            } else {
431                writeln!(
432                    &mut io::stdout(),
433                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
434                     list.",
435                );
436            }
437        }
438        "pid" => {
439            writeln!(
440                &mut io::stdout(),
441                "PID: {}",
442                sysinfo::get_current_pid().expect("failed to get PID")
443            );
444        }
445        "system" => {
446            writeln!(
447                &mut io::stdout(),
448                "System name:              {}\n\
449                 System kernel version:    {}\n\
450                 System OS version:        {}\n\
451                 System OS (long) version: {}\n\
452                 System host name:         {}\n\
453		 System kernel:            {}",
454                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
455                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
456                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
457                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
458                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
459                System::kernel_long_version(),
460            );
461        }
462        e => {
463            writeln!(
464                &mut io::stdout(),
465                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
466                 list.",
467            );
468        }
469    }
470    false
471}
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<u32>

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 (except on FreeBSD).

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 293)
150fn interpret_input(
151    input: &str,
152    sys: &mut System,
153    networks: &mut Networks,
154    disks: &mut Disks,
155    components: &mut Components,
156    users: &mut Users,
157) -> bool {
158    match input.trim() {
159        "help" => print_help(),
160        "refresh_disks" => {
161            writeln!(&mut io::stdout(), "Refreshing disk list...");
162            disks.refresh(true);
163            writeln!(&mut io::stdout(), "Done.");
164        }
165        "refresh_users" => {
166            writeln!(&mut io::stdout(), "Refreshing user list...");
167            users.refresh();
168            writeln!(&mut io::stdout(), "Done.");
169        }
170        "refresh_networks" => {
171            writeln!(&mut io::stdout(), "Refreshing network list...");
172            networks.refresh(true);
173            writeln!(&mut io::stdout(), "Done.");
174        }
175        "refresh_components" => {
176            writeln!(&mut io::stdout(), "Refreshing component list...");
177            components.refresh(true);
178            writeln!(&mut io::stdout(), "Done.");
179        }
180        "refresh_cpu" => {
181            writeln!(&mut io::stdout(), "Refreshing CPUs...");
182            sys.refresh_cpu_all();
183            writeln!(&mut io::stdout(), "Done.");
184        }
185        "signals" => {
186            let mut nb = 1i32;
187
188            for sig in signals {
189                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
190                nb += 1;
191            }
192        }
193        "cpus" => {
194            // Note: you should refresh a few times before using this, so that usage statistics
195            // can be ascertained
196            writeln!(
197                &mut io::stdout(),
198                "number of physical cores: {}",
199                System::physical_core_count()
200                    .map(|c| c.to_string())
201                    .unwrap_or_else(|| "Unknown".to_owned()),
202            );
203            writeln!(
204                &mut io::stdout(),
205                "total CPU usage: {}%",
206                sys.global_cpu_usage(),
207            );
208            for cpu in sys.cpus() {
209                writeln!(&mut io::stdout(), "{cpu:?}");
210            }
211        }
212        "memory" => {
213            writeln!(
214                &mut io::stdout(),
215                "total memory:     {: >10} KB",
216                sys.total_memory() / 1_000
217            );
218            writeln!(
219                &mut io::stdout(),
220                "available memory: {: >10} KB",
221                sys.available_memory() / 1_000
222            );
223            writeln!(
224                &mut io::stdout(),
225                "used memory:      {: >10} KB",
226                sys.used_memory() / 1_000
227            );
228            writeln!(
229                &mut io::stdout(),
230                "total swap:       {: >10} KB",
231                sys.total_swap() / 1_000
232            );
233            writeln!(
234                &mut io::stdout(),
235                "used swap:        {: >10} KB",
236                sys.used_swap() / 1_000
237            );
238        }
239        "quit" | "exit" => return true,
240        "all" => {
241            for (pid, proc_) in sys.processes() {
242                writeln!(
243                    &mut io::stdout(),
244                    "{}:{} status={:?}",
245                    pid,
246                    proc_.name().to_string_lossy(),
247                    proc_.status()
248                );
249            }
250        }
251        "frequency" => {
252            for cpu in sys.cpus() {
253                writeln!(
254                    &mut io::stdout(),
255                    "[{}] {} MHz",
256                    cpu.name(),
257                    cpu.frequency(),
258                );
259            }
260        }
261        "vendor_id" => {
262            writeln!(
263                &mut io::stdout(),
264                "vendor ID: {}",
265                sys.cpus()[0].vendor_id()
266            );
267        }
268        "brand" => {
269            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
270        }
271        "load_avg" => {
272            let load_avg = System::load_average();
273            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
274            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
275            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
276        }
277        e if e.starts_with("show ") => {
278            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
279
280            if tmp.len() != 2 {
281                writeln!(
282                    &mut io::stdout(),
283                    "show command takes a pid or a name in parameter!"
284                );
285                writeln!(&mut io::stdout(), "example: show 1254");
286            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
287                match sys.process(pid) {
288                    Some(p) => {
289                        writeln!(&mut io::stdout(), "{:?}", *p);
290                        writeln!(
291                            &mut io::stdout(),
292                            "Files open/limit: {:?}/{:?}",
293                            p.open_files(),
294                            p.open_files_limit(),
295                        );
296                    }
297                    None => {
298                        writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found");
299                    }
300                }
301            } else {
302                let proc_name = tmp[1];
303                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
304                    writeln!(
305                        &mut io::stdout(),
306                        "==== {} ====",
307                        proc_.name().to_string_lossy()
308                    );
309                    writeln!(&mut io::stdout(), "{proc_:?}");
310                }
311            }
312        }
313        "temperature" => {
314            for component in components.iter() {
315                writeln!(&mut io::stdout(), "{component:?}");
316            }
317        }
318        "network" => {
319            for (interface_name, data) in networks.iter() {
320                writeln!(
321                    &mut io::stdout(),
322                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
323                    interface_name,
324                    data.mac_address(),
325                    data.received(),
326                    data.total_received(),
327                    data.transmitted(),
328                    data.total_transmitted(),
329                );
330            }
331        }
332        "show" => {
333            writeln!(
334                &mut io::stdout(),
335                "'show' command expects a pid number or a process name"
336            );
337        }
338        e if e.starts_with("kill ") => {
339            let tmp: Vec<&str> = e.split(' ').collect();
340
341            if tmp.len() != 3 {
342                writeln!(
343                    &mut io::stdout(),
344                    "kill command takes the pid and a signal number in parameter!"
345                );
346                writeln!(&mut io::stdout(), "example: kill 1254 9");
347            } else {
348                let pid = Pid::from_str(tmp[1]).unwrap();
349                let signal = i32::from_str(tmp[2]).unwrap();
350
351                if signal < 1 || signal > 31 {
352                    writeln!(
353                        &mut io::stdout(),
354                        "Signal must be between 0 and 32 ! See the signals list with the \
355                         signals command"
356                    );
357                } else {
358                    match sys.process(pid) {
359                        Some(p) => {
360                            if let Some(res) =
361                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
362                            {
363                                writeln!(&mut io::stdout(), "kill: {res}");
364                            } else {
365                                writeln!(
366                                    &mut io::stdout(),
367                                    "kill: signal not supported on this platform"
368                                );
369                            }
370                        }
371                        None => {
372                            writeln!(&mut io::stdout(), "pid not found");
373                        }
374                    };
375                }
376            }
377        }
378        "disks" => {
379            for disk in disks {
380                writeln!(&mut io::stdout(), "{disk:?}");
381            }
382        }
383        "users" => {
384            for user in users {
385                writeln!(
386                    &mut io::stdout(),
387                    "{:?} => {:?}",
388                    user.name(),
389                    user.groups()
390                );
391            }
392        }
393        "boot_time" => {
394            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
395        }
396        "uptime" => {
397            let up = System::uptime();
398            let mut uptime = up;
399            let days = uptime / 86400;
400            uptime -= days * 86400;
401            let hours = uptime / 3600;
402            uptime -= hours * 3600;
403            let minutes = uptime / 60;
404            writeln!(
405                &mut io::stdout(),
406                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
407            );
408        }
409        x if x.starts_with("refresh") => {
410            if x == "refresh" {
411                writeln!(&mut io::stdout(), "Getting processes' information...");
412                sys.refresh_all();
413                writeln!(&mut io::stdout(), "Done.");
414            } else if x.starts_with("refresh ") {
415                writeln!(&mut io::stdout(), "Getting process' information...");
416                if let Some(pid) = x
417                    .split(' ')
418                    .filter_map(|pid| pid.parse().ok())
419                    .take(1)
420                    .next()
421                {
422                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
423                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
424                    } else {
425                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
426                    }
427                } else {
428                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
429                }
430            } else {
431                writeln!(
432                    &mut io::stdout(),
433                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
434                     list.",
435                );
436            }
437        }
438        "pid" => {
439            writeln!(
440                &mut io::stdout(),
441                "PID: {}",
442                sysinfo::get_current_pid().expect("failed to get PID")
443            );
444        }
445        "system" => {
446            writeln!(
447                &mut io::stdout(),
448                "System name:              {}\n\
449                 System kernel version:    {}\n\
450                 System OS version:        {}\n\
451                 System OS (long) version: {}\n\
452                 System host name:         {}\n\
453		 System kernel:            {}",
454                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
455                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
456                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
457                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
458                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
459                System::kernel_long_version(),
460            );
461        }
462        e => {
463            writeln!(
464                &mut io::stdout(),
465                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
466                 list.",
467            );
468        }
469    }
470    false
471}
Source

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

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 294)
150fn interpret_input(
151    input: &str,
152    sys: &mut System,
153    networks: &mut Networks,
154    disks: &mut Disks,
155    components: &mut Components,
156    users: &mut Users,
157) -> bool {
158    match input.trim() {
159        "help" => print_help(),
160        "refresh_disks" => {
161            writeln!(&mut io::stdout(), "Refreshing disk list...");
162            disks.refresh(true);
163            writeln!(&mut io::stdout(), "Done.");
164        }
165        "refresh_users" => {
166            writeln!(&mut io::stdout(), "Refreshing user list...");
167            users.refresh();
168            writeln!(&mut io::stdout(), "Done.");
169        }
170        "refresh_networks" => {
171            writeln!(&mut io::stdout(), "Refreshing network list...");
172            networks.refresh(true);
173            writeln!(&mut io::stdout(), "Done.");
174        }
175        "refresh_components" => {
176            writeln!(&mut io::stdout(), "Refreshing component list...");
177            components.refresh(true);
178            writeln!(&mut io::stdout(), "Done.");
179        }
180        "refresh_cpu" => {
181            writeln!(&mut io::stdout(), "Refreshing CPUs...");
182            sys.refresh_cpu_all();
183            writeln!(&mut io::stdout(), "Done.");
184        }
185        "signals" => {
186            let mut nb = 1i32;
187
188            for sig in signals {
189                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
190                nb += 1;
191            }
192        }
193        "cpus" => {
194            // Note: you should refresh a few times before using this, so that usage statistics
195            // can be ascertained
196            writeln!(
197                &mut io::stdout(),
198                "number of physical cores: {}",
199                System::physical_core_count()
200                    .map(|c| c.to_string())
201                    .unwrap_or_else(|| "Unknown".to_owned()),
202            );
203            writeln!(
204                &mut io::stdout(),
205                "total CPU usage: {}%",
206                sys.global_cpu_usage(),
207            );
208            for cpu in sys.cpus() {
209                writeln!(&mut io::stdout(), "{cpu:?}");
210            }
211        }
212        "memory" => {
213            writeln!(
214                &mut io::stdout(),
215                "total memory:     {: >10} KB",
216                sys.total_memory() / 1_000
217            );
218            writeln!(
219                &mut io::stdout(),
220                "available memory: {: >10} KB",
221                sys.available_memory() / 1_000
222            );
223            writeln!(
224                &mut io::stdout(),
225                "used memory:      {: >10} KB",
226                sys.used_memory() / 1_000
227            );
228            writeln!(
229                &mut io::stdout(),
230                "total swap:       {: >10} KB",
231                sys.total_swap() / 1_000
232            );
233            writeln!(
234                &mut io::stdout(),
235                "used swap:        {: >10} KB",
236                sys.used_swap() / 1_000
237            );
238        }
239        "quit" | "exit" => return true,
240        "all" => {
241            for (pid, proc_) in sys.processes() {
242                writeln!(
243                    &mut io::stdout(),
244                    "{}:{} status={:?}",
245                    pid,
246                    proc_.name().to_string_lossy(),
247                    proc_.status()
248                );
249            }
250        }
251        "frequency" => {
252            for cpu in sys.cpus() {
253                writeln!(
254                    &mut io::stdout(),
255                    "[{}] {} MHz",
256                    cpu.name(),
257                    cpu.frequency(),
258                );
259            }
260        }
261        "vendor_id" => {
262            writeln!(
263                &mut io::stdout(),
264                "vendor ID: {}",
265                sys.cpus()[0].vendor_id()
266            );
267        }
268        "brand" => {
269            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
270        }
271        "load_avg" => {
272            let load_avg = System::load_average();
273            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
274            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
275            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
276        }
277        e if e.starts_with("show ") => {
278            let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
279
280            if tmp.len() != 2 {
281                writeln!(
282                    &mut io::stdout(),
283                    "show command takes a pid or a name in parameter!"
284                );
285                writeln!(&mut io::stdout(), "example: show 1254");
286            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
287                match sys.process(pid) {
288                    Some(p) => {
289                        writeln!(&mut io::stdout(), "{:?}", *p);
290                        writeln!(
291                            &mut io::stdout(),
292                            "Files open/limit: {:?}/{:?}",
293                            p.open_files(),
294                            p.open_files_limit(),
295                        );
296                    }
297                    None => {
298                        writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found");
299                    }
300                }
301            } else {
302                let proc_name = tmp[1];
303                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
304                    writeln!(
305                        &mut io::stdout(),
306                        "==== {} ====",
307                        proc_.name().to_string_lossy()
308                    );
309                    writeln!(&mut io::stdout(), "{proc_:?}");
310                }
311            }
312        }
313        "temperature" => {
314            for component in components.iter() {
315                writeln!(&mut io::stdout(), "{component:?}");
316            }
317        }
318        "network" => {
319            for (interface_name, data) in networks.iter() {
320                writeln!(
321                    &mut io::stdout(),
322                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
323                    interface_name,
324                    data.mac_address(),
325                    data.received(),
326                    data.total_received(),
327                    data.transmitted(),
328                    data.total_transmitted(),
329                );
330            }
331        }
332        "show" => {
333            writeln!(
334                &mut io::stdout(),
335                "'show' command expects a pid number or a process name"
336            );
337        }
338        e if e.starts_with("kill ") => {
339            let tmp: Vec<&str> = e.split(' ').collect();
340
341            if tmp.len() != 3 {
342                writeln!(
343                    &mut io::stdout(),
344                    "kill command takes the pid and a signal number in parameter!"
345                );
346                writeln!(&mut io::stdout(), "example: kill 1254 9");
347            } else {
348                let pid = Pid::from_str(tmp[1]).unwrap();
349                let signal = i32::from_str(tmp[2]).unwrap();
350
351                if signal < 1 || signal > 31 {
352                    writeln!(
353                        &mut io::stdout(),
354                        "Signal must be between 0 and 32 ! See the signals list with the \
355                         signals command"
356                    );
357                } else {
358                    match sys.process(pid) {
359                        Some(p) => {
360                            if let Some(res) =
361                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
362                            {
363                                writeln!(&mut io::stdout(), "kill: {res}");
364                            } else {
365                                writeln!(
366                                    &mut io::stdout(),
367                                    "kill: signal not supported on this platform"
368                                );
369                            }
370                        }
371                        None => {
372                            writeln!(&mut io::stdout(), "pid not found");
373                        }
374                    };
375                }
376            }
377        }
378        "disks" => {
379            for disk in disks {
380                writeln!(&mut io::stdout(), "{disk:?}");
381            }
382        }
383        "users" => {
384            for user in users {
385                writeln!(
386                    &mut io::stdout(),
387                    "{:?} => {:?}",
388                    user.name(),
389                    user.groups()
390                );
391            }
392        }
393        "boot_time" => {
394            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
395        }
396        "uptime" => {
397            let up = System::uptime();
398            let mut uptime = up;
399            let days = uptime / 86400;
400            uptime -= days * 86400;
401            let hours = uptime / 3600;
402            uptime -= hours * 3600;
403            let minutes = uptime / 60;
404            writeln!(
405                &mut io::stdout(),
406                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
407            );
408        }
409        x if x.starts_with("refresh") => {
410            if x == "refresh" {
411                writeln!(&mut io::stdout(), "Getting processes' information...");
412                sys.refresh_all();
413                writeln!(&mut io::stdout(), "Done.");
414            } else if x.starts_with("refresh ") {
415                writeln!(&mut io::stdout(), "Getting process' information...");
416                if let Some(pid) = x
417                    .split(' ')
418                    .filter_map(|pid| pid.parse().ok())
419                    .take(1)
420                    .next()
421                {
422                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
423                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
424                    } else {
425                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
426                    }
427                } else {
428                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
429                }
430            } else {
431                writeln!(
432                    &mut io::stdout(),
433                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
434                     list.",
435                );
436            }
437        }
438        "pid" => {
439            writeln!(
440                &mut io::stdout(),
441                "PID: {}",
442                sysinfo::get_current_pid().expect("failed to get PID")
443            );
444        }
445        "system" => {
446            writeln!(
447                &mut io::stdout(),
448                "System name:              {}\n\
449                 System kernel version:    {}\n\
450                 System OS version:        {}\n\
451                 System OS (long) version: {}\n\
452                 System host name:         {}\n\
453		 System kernel:            {}",
454                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
455                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
456                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
457                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
458                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
459                System::kernel_long_version(),
460            );
461        }
462        e => {
463            writeln!(
464                &mut io::stdout(),
465                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
466                 list.",
467            );
468        }
469    }
470    false
471}

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.