pub struct System { /* private fields */ }Expand description
Type containing system’s information such as processes, memory and CPU.
⚠️ On newer Android versions, there are restrictions on which system information a non-system application has access to. So CPU information might not be available.
use sysinfo::System;
match System::new_all() {
Ok(system) => println!("System: {system:?}"),
Err(error) => println!("Failed to initialize system: {error:?}"),
}Implementations§
Source§impl System
impl System
Sourcepub fn new() -> Result<Self, Error>
pub fn new() -> Result<Self, Error>
Creates a new System instance with nothing loaded.
Use one of the refresh methods (like refresh_all) to update its internal information.
use sysinfo::System;
let Ok(s) = System::new() else {
println!("Failed to initialize `System`");
return;
};Sourcepub fn new_all() -> Result<Self, Error>
pub fn new_all() -> Result<Self, Error>
Creates a new System instance with everything loaded.
It is an equivalent of System::new_with_specifics(RefreshKind::everything()).
use sysinfo::System;
let Ok(s) = System::new_all() else {
println!("Failed to initialize `System`");
return;
};Examples found in repository?
507fn main() {
508 println!("Getting system information...");
509 let mut system = System::new_all();
510 let mut networks = Networks::new_with_refreshed_list();
511 let mut disks = Disks::new_with_refreshed_list();
512 let mut components = Components::new_with_refreshed_list();
513 let mut users = Users::new_with_refreshed_list();
514 let mut gpus = Gpus::new();
515
516 println!("Done.");
517 let t_stin = io::stdin();
518 let mut stin = t_stin.lock();
519 let mut done = false;
520
521 println!("To get the commands' list, enter 'help'.");
522 while !done {
523 let mut input = String::new();
524 write!(&mut io::stdout(), "> ");
525 io::stdout().flush();
526
527 stin.read_line(&mut input);
528 if input.is_empty() {
529 // The string is empty, meaning there is no '\n', meaning
530 // that the user used CTRL+D so we can just quit!
531 println!("\nLeaving, bye!");
532 break;
533 }
534 if (&input as &str).ends_with('\n') {
535 input.pop();
536 }
537 done = interpret_input(
538 input.as_ref(),
539 system.as_mut(),
540 gpus.as_mut(),
541 networks.as_mut(),
542 disks.as_mut(),
543 components.as_mut(),
544 users.as_mut(),
545 );
546 }
547}Sourcepub fn new_with_specifics(refreshes: RefreshKind) -> Result<Self, Error>
pub fn new_with_specifics(refreshes: RefreshKind) -> Result<Self, Error>
Creates a new System instance and refresh the data corresponding to the
given RefreshKind.
use sysinfo::{ProcessRefreshKind, RefreshKind, System};
// We want to only refresh processes.
if let Ok(mut system) = System::new_with_specifics(
RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
) {
assert!(!system.processes().is_empty());
}Sourcepub fn refresh_specifics(&mut self, refreshes: RefreshKind)
pub fn refresh_specifics(&mut self, refreshes: RefreshKind)
Refreshes according to the given RefreshKind. It calls the corresponding
“refresh_” methods.
It will remove dead processes if RefreshKind::processes returns Some.
If you want to keep dead processes, use System::refresh_processes_specifics
directly.
use sysinfo::{ProcessRefreshKind, RefreshKind, System};
if let Ok(mut s) = System::new_all() {
// Let's just update processes:
s.refresh_specifics(
RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
);
}Sourcepub fn refresh_all(&mut self)
pub fn refresh_all(&mut self)
Refreshes all system and processes information.
It is the same as calling system.refresh_specifics(RefreshKind::everything()).
Don’t forget to take a look at ProcessRefreshKind::everything method to see what it
will update for processes more in details.
It will remove dead processes. If you want to keep dead processes, use
System::refresh_processes_specifics directly.
use sysinfo::System;
if let Ok(mut s) = System::new() {
s.refresh_all();
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn refresh_memory(&mut self)
pub fn refresh_memory(&mut self)
Refreshes RAM and SWAP usage.
It is the same as calling system.refresh_memory_specifics(MemoryRefreshKind::everything()).
If you don’t want to refresh both, take a look at System::refresh_memory_specifics.
use sysinfo::System;
if let Ok(mut s) = System::new() {
s.refresh_memory();
}Sourcepub fn refresh_memory_specifics(&mut self, refresh_kind: MemoryRefreshKind)
pub fn refresh_memory_specifics(&mut self, refresh_kind: MemoryRefreshKind)
Refreshes system memory specific information.
use sysinfo::{MemoryRefreshKind, System};
if let Ok(mut s) = System::new() {
s.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
}Sourcepub fn refresh_cpu_usage(&mut self)
pub fn refresh_cpu_usage(&mut self)
Refreshes CPUs usage.
⚠️ Please note that the result will very likely be inaccurate at the first call.
You need to call this method at least twice (with a bit of time between each call, like
200 ms, take a look at MINIMUM_CPU_UPDATE_INTERVAL for more information)
to get accurate value as it uses previous results to compute the next value.
Calling this method is the same as calling
system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_usage()).
use sysinfo::System;
if let Ok(mut s) = System::new_all() {
// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPUs again.
s.refresh_cpu_usage();
}Sourcepub fn refresh_cpu_frequency(&mut self)
pub fn refresh_cpu_frequency(&mut self)
Refreshes CPUs frequency information.
Calling this method is the same as calling
system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_frequency()).
use sysinfo::System;
if let Ok(mut s) = System::new_all() {
s.refresh_cpu_frequency();
}Sourcepub fn refresh_cpu_list(&mut self, refresh_kind: CpuRefreshKind)
pub fn refresh_cpu_list(&mut self, refresh_kind: CpuRefreshKind)
Refreshes the list of CPU.
Normally, this should almost never be needed as it’s pretty rare for a computer to add a CPU while running, but it’s possible on some computers which shutdown CPU if the load is low enough.
The refresh_kind argument tells what information you want to be retrieved
for each CPU.
use sysinfo::{CpuRefreshKind, System};
if let Ok(mut s) = System::new_all() {
// We already have the list of CPU filled, but we want to recompute it
// in case new CPUs were added.
s.refresh_cpu_list(CpuRefreshKind::everything());
}Sourcepub fn refresh_cpu_all(&mut self)
pub fn refresh_cpu_all(&mut self)
Refreshes all information related to CPUs information. It does not refresh the CPU list.
If you want to refresh the CPU list, use System::refresh_cpu_list instead.
If you only want the CPU usage, use System::refresh_cpu_usage instead.
⚠️ Please note that the result will be inaccurate at the first call.
You need to call this method at least twice (with a bit of time between each call, like
200 ms, take a look at MINIMUM_CPU_UPDATE_INTERVAL for more information)
to get accurate value as it uses previous results to compute the next value.
Calling this method is the same as calling
system.refresh_cpu_specifics(CpuRefreshKind::everything()).
use sysinfo::System;
if let Ok(mut s) = System::new_all() {
s.refresh_cpu_all();
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn refresh_cpu_specifics(&mut self, refresh_kind: CpuRefreshKind)
pub fn refresh_cpu_specifics(&mut self, refresh_kind: CpuRefreshKind)
Refreshes CPUs specific information. It does not refresh the CPU list.
If you want to refresh the CPU list, use System::refresh_cpu_list instead.
use sysinfo::{System, CpuRefreshKind};
if let Ok(mut s) = System::new_all() {
s.refresh_cpu_specifics(CpuRefreshKind::everything());
}Sourcepub fn refresh_processes(
&mut self,
processes_to_update: ProcessesToUpdate<'_>,
remove_dead_processes: bool,
) -> usize
pub fn refresh_processes( &mut self, processes_to_update: ProcessesToUpdate<'_>, remove_dead_processes: bool, ) -> usize
Gets all processes and updates their information, along with all the tasks each process has.
It does the same as:
system.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing()
.with_memory()
.with_cpu()
.with_disk_usage()
.with_exe(UpdateKind::OnlyIfNotSet)
.with_tasks()
);⚠️ remove_dead_processes works as follows: if an updated process is dead, then it is
removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed
since 7 is not part of the update.
⚠️ On Linux, if you dont need the tasks of each process, you can use
refresh_processes_specifics with ProcessRefreshKind::everything().without_tasks().
Refreshing all processes and their tasks can be quite expensive. For more information
see ProcessRefreshKind.
Example:
use sysinfo::{ProcessesToUpdate, System};
if let Ok(mut s) = System::new_all() {
s.refresh_processes(ProcessesToUpdate::All, true);
}Sourcepub fn refresh_processes_specifics(
&mut self,
processes_to_update: ProcessesToUpdate<'_>,
remove_dead_processes: bool,
refresh_kind: ProcessRefreshKind,
) -> usize
pub fn refresh_processes_specifics( &mut self, processes_to_update: ProcessesToUpdate<'_>, remove_dead_processes: bool, refresh_kind: ProcessRefreshKind, ) -> usize
Gets all processes and updates the specified information.
Returns the number of updated processes.
⚠️ remove_dead_processes works as follows: if an updated process is dead, then it is
removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed
since 7 is not part of the update.
use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System};
if let Ok(mut s) = System::new_all() {
s.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::everything(),
);
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn processes(&self) -> &HashMap<Pid, Process>
pub fn processes(&self) -> &HashMap<Pid, Process>
Returns the process list.
use sysinfo::System;
if let Ok(s) = System::new_all() {
for (pid, process) in s.processes() {
println!("{} {:?}", pid, process.name());
}
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn process(&self, pid: Pid) -> Option<&Process>
pub fn process(&self, pid: Pid) -> Option<&Process>
Returns the process corresponding to the given pid or None if no such process exists.
use sysinfo::{Pid, System};
if let Ok(s) = System::new_all() {
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.name());
}
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn processes_by_name<'a: 'b, 'b>(
&'a self,
name: &'b OsStr,
) -> impl Iterator<Item = &'a Process> + 'b
pub fn processes_by_name<'a: 'b, 'b>( &'a self, name: &'b OsStr, ) -> impl Iterator<Item = &'a Process> + 'b
Returns an iterator of process containing the given name.
If you want only the processes with exactly the given name, take a look at
System::processes_by_exact_name.
⚠️ Important ⚠️
On Linux, there are two things to know about processes’ name:
- It is limited to 15 characters.
- It is not always the exe name.
use sysinfo::System;
if let Ok(s) = System::new_all() {
for process in s.processes_by_name("htop".as_ref()) {
println!("{} {:?}", process.pid(), process.name());
}
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn processes_by_exact_name<'a: 'b, 'b>(
&'a self,
name: &'b OsStr,
) -> impl Iterator<Item = &'a Process> + 'b
pub fn processes_by_exact_name<'a: 'b, 'b>( &'a self, name: &'b OsStr, ) -> impl Iterator<Item = &'a Process> + 'b
Returns an iterator of processes with exactly the given name.
If you instead want the processes containing name, take a look at
System::processes_by_name.
⚠️ Important ⚠️
On Linux, there are two things to know about processes’ name:
- It is limited to 15 characters.
- It is not always the exe name.
use sysinfo::System;
if let Ok(s) = System::new_all() {
for process in s.processes_by_exact_name("htop".as_ref()) {
println!("{} {:?}", process.pid(), process.name());
}
}Sourcepub fn global_cpu_usage(&self) -> f32
pub fn global_cpu_usage(&self) -> f32
Returns “global” CPUs usage (aka the addition of all the CPUs).
To have up-to-date information, you need to call System::refresh_cpu_specifics or
System::refresh_specifics with cpu enabled.
use sysinfo::{CpuRefreshKind, RefreshKind, System};
if let Ok(mut s) = System::new_with_specifics(
RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
) {
// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPUs again to get actual value.
s.refresh_cpu_usage();
println!("{}%", s.global_cpu_usage());
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn cpus(&self) -> &[Cpu]
pub fn cpus(&self) -> &[Cpu]
Returns the list of the CPUs.
By default, the list of CPUs is empty until you call System::refresh_cpu_specifics or
System::refresh_specifics with cpu enabled.
use sysinfo::{CpuRefreshKind, RefreshKind, System};
if let Ok(mut s) = System::new_with_specifics(
RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
) {
// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPUs again to get actual value.
s.refresh_cpu_usage();
for cpu in s.cpus() {
println!("{}%", cpu.usage());
}
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn total_memory(&self) -> u64
pub fn total_memory(&self) -> u64
Returns the RAM size in bytes.
use sysinfo::System;
if let Ok(s) = System::new_all() {
println!("{} bytes", s.total_memory());
}On Linux, if you want to see this information with the limit of your cgroup, take a look
at cgroup_limits.
Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn free_memory(&self) -> u64
pub fn free_memory(&self) -> u64
Returns the amount of free RAM in bytes.
Generally, “free” memory refers to unallocated memory whereas “available” memory refers to memory that is available for (re)use.
Side note: Windows doesn’t report “free” memory so this method returns the same value
as available_memory.
use sysinfo::System;
if let Ok(s) = System::new_all() {
println!("{} bytes", s.free_memory());
}Sourcepub fn available_memory(&self) -> u64
pub fn available_memory(&self) -> u64
Returns the amount of available RAM in bytes.
Generally, “free” memory refers to unallocated memory whereas “available” memory refers to memory that is available for (re)use.
⚠️ Windows doesn’t report “available” memory so System::free_memory
returns the same value as this method.
use sysinfo::System;
if let Ok(s) = System::new_all() {
println!("{} bytes", s.available_memory());
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn used_memory(&self) -> u64
pub fn used_memory(&self) -> u64
Returns the amount of used RAM in bytes.
use sysinfo::System;
if let Ok(s) = System::new_all() {
println!("{} bytes", s.used_memory());
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn total_swap(&self) -> u64
pub fn total_swap(&self) -> u64
Returns the SWAP size in bytes.
use sysinfo::System;
if let Ok(s) = System::new_all() {
println!("{} bytes", s.total_swap());
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn free_swap(&self) -> u64
pub fn free_swap(&self) -> u64
Returns the amount of free SWAP in bytes.
use sysinfo::System;
if let Ok(s) = System::new_all() {
println!("{} bytes", s.free_swap());
}Sourcepub fn used_swap(&self) -> u64
pub fn used_swap(&self) -> u64
Returns the amount of used SWAP in bytes.
use sysinfo::System;
if let Ok(s) = System::new_all() {
println!("{} bytes", s.used_swap());
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn cgroup_limits(&self) -> Option<CGroupLimits>
pub fn cgroup_limits(&self) -> Option<CGroupLimits>
Retrieves the limits for the root cgroup (if any), otherwise it returns None.
This information is computed every time the method is called.
⚠️ This method is only implemented for Linux. It always returns None for all other
systems.
use sysinfo::System;
if let Ok(s) = System::new_all() {
println!("limits: {:?}", s.cgroup_limits());
}Sourcepub fn uptime() -> Result<u64, Error>
pub fn uptime() -> Result<u64, Error>
Returns system uptime (in seconds).
Important: this information is computed every time this function is called.
use sysinfo::System;
match System::uptime() {
Ok(uptime) => println!("System running since {uptime} seconds"),
Err(error) => eprintln!("Failed to get `uptime`: {error}"),
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn boot_time() -> Result<u64, Error>
pub fn boot_time() -> Result<u64, Error>
Returns the time (in seconds) when the system booted since UNIX epoch.
Important: this information is computed every time this function is called.
use sysinfo::System;
match System::boot_time() {
Ok(boot_time) => println!("System booted at {boot_time} seconds"),
Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn load_average() -> Result<LoadAvg, Error>
pub fn load_average() -> Result<LoadAvg, Error>
Returns the system load average value.
Important: this information is computed every time this function is called.
⚠️ This is currently not working on Windows.
use sysinfo::System;
match System::load_average() {
Ok(load_avg) => {
println!(
"one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
load_avg.one,
load_avg.five,
load_avg.fifteen,
);
}
Err(error) => eprintln!("Failed to get `load_average`: {error}"),
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn name() -> Result<String, Error>
pub fn name() -> Result<String, Error>
Returns the system name.
| example platform | value of System::name() |
|---|---|
| linux laptop | “Ubuntu” |
| android phone | “Pixel 9 Pro” |
| apple laptop | “Darwin” |
| windows server | “Windows” |
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("OS: {:?}", System::name());Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn kernel_version() -> Result<String, Error>
pub fn kernel_version() -> Result<String, Error>
Returns the system’s kernel version.
| example platform | value of System::kernel_version() |
|---|---|
| linux laptop | “6.8.0-48-generic” |
| android phone | “6.1.84-android14-11” |
| apple laptop | “24.1.0” |
| windows server | “20348” |
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("kernel version: {:?}", System::kernel_version());Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn os_version() -> Result<String, Error>
pub fn os_version() -> Result<String, Error>
Returns the system version (e.g. for macOS this will return 15.1 rather than the kernel version).
| example platform | value of System::os_version() |
|---|---|
| linux laptop | “24.04” |
| android phone | “15” |
| apple laptop | “15.1.1” |
| windows server | “10 (20348)” |
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("OS version: {:?}", System::os_version());Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn long_os_version() -> Result<String, Error>
pub fn long_os_version() -> Result<String, Error>
Returns the system long os version.
| example platform | value of System::long_os_version() |
|---|---|
| linux laptop | “Linux (Ubuntu 24.04)” |
| android phone | “Android 15 on Pixel 9 Pro” |
| apple laptop | “macOS 15.1.1 Sequoia” |
| windows server | “Windows Server 2022 Datacenter” |
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("Long OS Version: {:?}", System::long_os_version());Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn distribution_id() -> String
pub fn distribution_id() -> String
Returns the distribution id as defined by os-release,
or [std::env::consts::OS].
See also
- https://www.freedesktop.org/software/systemd/man/os-release.html#ID=
- https://doc.rust-lang.org/std/env/consts/constant.OS.html
| example platform | value of System::distribution_id() |
|---|---|
| linux laptop | “ubuntu” |
| android phone | “android” |
| apple laptop | “macos” |
| windows server | “windows” |
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("Distribution ID: {:?}", System::distribution_id());Sourcepub fn distribution_id_like() -> Vec<String>
pub fn distribution_id_like() -> Vec<String>
Returns the distribution ids of operating systems that are closely related to the local operating system in regards to packaging and programming interfaces, for example listing one or more OS identifiers the local OS is a derivative from.
See also
| example platform | value of System::distribution_id_like() |
|---|---|
| android phone | [] |
| archlinux laptop | [] |
| centos server | [“rhel”, “fedora”] |
| ubuntu laptop | [“debian”] |
| windows laptop | [] |
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("Distribution ID_LIKE: {:?}", System::distribution_id_like());Sourcepub fn kernel_long_version() -> Result<String, Error>
pub fn kernel_long_version() -> Result<String, Error>
Provides kernel version following this string format:
| Platform | Result |
|---|---|
| Windows | Windows OS Build 20348.2227 |
| Linux | Linux 6.12.13-200.fc41.x86_64 |
| Android | Android 612.13-200 |
| MacOS | Darwin 21.6.0 |
| FreeBSD | FreeBSD 199506 |
If any of the information is not available, it will be replaced with “unknown”.
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("Kernel long version: {:?}", System::kernel_long_version());Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn host_name() -> Result<String, Error>
pub fn host_name() -> Result<String, Error>
Returns the system hostname based off DNS.
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("Hostname: {:?}", System::host_name());Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn cpu_arch() -> String
pub fn cpu_arch() -> String
Returns the CPU architecture (eg. x86, amd64, aarch64, …).
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("CPU Architecture: {:?}", System::cpu_arch());Sourcepub fn physical_core_count() -> Result<usize, Error>
pub fn physical_core_count() -> Result<usize, Error>
Returns the number of physical cores on the CPU.
In case there are multiple CPUs, it will combine the physical core count of all the CPUs.
Important: this information is computed every time this function is called.
use sysinfo::System;
if let Ok(s) = System::new() {
println!("{:?}", System::physical_core_count());
}Examples found in repository?
74fn interpret_input(
75 input: &str,
76 sys: Result<&mut System, &mut Error>,
77 gpus: Result<&mut Gpus, &mut Error>,
78 networks: Result<&mut Networks, &mut Error>,
79 disks: Result<&mut Disks, &mut Error>,
80 components: Result<&mut Components, &mut Error>,
81 users: Result<&mut Users, &mut Error>,
82) -> bool {
83 match input.trim() {
84 "help" => print_help(),
85 "refresh_disks" => match disks {
86 Ok(disks) => {
87 println!("Refreshing disk list...");
88 disks.refresh(true);
89 println!("Done.");
90 }
91 Err(error) => {
92 println!("Disks information cannot be retrieved: {error}");
93 }
94 },
95 "refresh_users" => match users {
96 Ok(users) => {
97 println!("Refreshing user list...");
98 users.refresh();
99 println!("Done.");
100 }
101 Err(error) => {
102 println!("Users information cannot be retrieved: {error}");
103 }
104 },
105 "refresh_networks" => match networks {
106 Ok(networks) => {
107 println!("Refreshing network list...");
108 networks.refresh(true);
109 println!("Done.");
110 }
111 Err(error) => {
112 println!("Networks information cannot be retrieved: {error}");
113 }
114 },
115 "refresh_components" => match components {
116 Ok(components) => {
117 println!("Refreshing component list...");
118 components.refresh(true);
119 println!("Done.");
120 }
121 Err(error) => {
122 println!("Components information cannot be retrieved: {error}");
123 }
124 },
125 "refresh_cpu" => match sys {
126 Ok(sys) => {
127 println!("Refreshing CPUs...");
128 sys.refresh_cpu_all();
129 println!("Done.");
130 }
131 Err(error) => {
132 println!("System information cannot be retrieved: {error}");
133 }
134 },
135 "signals" => {
136 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
137 println!("{:2}:{sig:?}", nb + 1);
138 }
139 }
140 "cpus" => {
141 match sys {
142 Ok(sys) => {
143 // Note: you should refresh a few times before using this, so that usage statistics
144 // can be ascertained
145 println!(
146 "number of physical cores: {}",
147 System::physical_core_count()
148 .map(|c| c.to_string())
149 .unwrap_or_else(|_| "Unknown".to_owned()),
150 );
151 println!("total CPU usage: {}%", sys.global_cpu_usage());
152 for cpu in sys.cpus() {
153 println!("{cpu:?}");
154 }
155 }
156 Err(error) => {
157 println!("System information cannot be retrieved: {error}");
158 }
159 }
160 }
161 "gpus" => match gpus {
162 Ok(gpus) => {
163 gpus.refresh(true);
164 for gpu in &*gpus {
165 println!(
166 "GPU (PCI: {}): Vendor: {}",
167 gpu.pci(),
168 gpu.vendor().unwrap_or("Unknown")
169 );
170 if let Some(model) = gpu.model() {
171 println!(" model: {model}");
172 }
173 match gpu.usage() {
174 Some(usage) => println!(" usage: {usage}%"),
175 None => println!(" usage: N/A"),
176 }
177 if let (Some(used), Some(total)) = (gpu.used_memory(), gpu.total_memory()) {
178 println!(" memory: {}/{} KB", used / 1_000, total / 1_000);
179 } else {
180 println!(" memory: N/A");
181 }
182 }
183 }
184 Err(error) => {
185 println!("GPU information cannot be retrieved on this system: {error}");
186 }
187 },
188 "memory" => match sys {
189 Ok(sys) => {
190 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
191 println!(
192 "available memory: {: >10} KB",
193 sys.available_memory() / 1_000
194 );
195 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
196 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
197 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
198 }
199 Err(error) => {
200 println!("System information cannot be retrieved: {error}");
201 }
202 },
203 "quit" | "exit" => return true,
204 "all" => match sys {
205 Ok(sys) => {
206 for (pid, proc_) in sys.processes() {
207 println!(
208 "{}:{} status={:?}",
209 pid,
210 proc_.name().to_string_lossy(),
211 proc_.status()
212 );
213 }
214 }
215 Err(error) => {
216 println!("System information cannot be retrieved: {error}");
217 }
218 },
219 "frequency" => match sys {
220 Ok(sys) => {
221 for cpu in sys.cpus() {
222 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
223 }
224 }
225 Err(error) => {
226 println!("System information cannot be retrieved: {error}");
227 }
228 },
229 "vendor_id" => match sys {
230 Ok(sys) => {
231 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
232 }
233 Err(error) => {
234 println!("System information cannot be retrieved: {error}");
235 }
236 },
237 "brand" => match sys {
238 Ok(sys) => {
239 println!("brand: {}", sys.cpus()[0].brand());
240 }
241 Err(error) => {
242 println!("System information cannot be retrieved: {error}");
243 }
244 },
245 "load_avg" => match System::load_average() {
246 Ok(load_avg) => {
247 println!("one minute : {}%", load_avg.one);
248 println!("five minutes : {}%", load_avg.five);
249 println!("fifteen minutes: {}%", load_avg.fifteen);
250 }
251 Err(error) => {
252 eprintln!("Failed to get `load_average`: {error}");
253 }
254 },
255 e if e.starts_with("show ") => {
256 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
257
258 if tmp.len() != 2 {
259 println!("show command takes a pid or a name in parameter!");
260 println!("example: show 1254");
261 } else {
262 match sys {
263 Ok(sys) => {
264 if let Ok(pid) = Pid::from_str(tmp[1]) {
265 match sys.process(pid) {
266 Some(p) => {
267 println!("{:#?}", *p);
268 println!(
269 "Files open/limit: {:?}/{:?}",
270 p.open_files(),
271 p.open_files_limit(),
272 );
273 }
274 None => {
275 println!("pid \"{pid:?}\" not found");
276 }
277 }
278 } else {
279 let proc_name = tmp[1];
280 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
281 println!("==== {} ====", proc_.name().to_string_lossy());
282 println!("{proc_:?}");
283 }
284 }
285 }
286 Err(error) => {
287 println!("System information cannot be retrieved: {error}");
288 }
289 }
290 }
291 }
292 "temperature" => match components {
293 Ok(components) => {
294 for component in components.iter() {
295 println!("{component:?}");
296 }
297 }
298 Err(error) => {
299 println!("Components information cannot be retrieved: {error}");
300 }
301 },
302 "network" => match networks {
303 Ok(networks) => {
304 for (interface_name, data) in networks.iter() {
305 println!(
306 "\
307 {}:
308 operational state {}
309 ether {}
310 input data (new / total): {} / {} B
311 output data (new / total): {} / {} B",
312 interface_name.display(),
313 data.operational_state(),
314 data.mac_address(),
315 data.received(),
316 data.total_received(),
317 data.transmitted(),
318 data.total_transmitted(),
319 );
320 }
321 }
322 Err(error) => {
323 println!("Networks information cannot be retrieved: {error}");
324 }
325 },
326 "show" => {
327 println!("'show' command expects a pid number or a process name");
328 }
329 e if e.starts_with("kill ") => {
330 let tmp: Vec<&str> = e
331 .split(' ')
332 .map(|s| s.trim())
333 .filter(|s| !s.is_empty())
334 .collect();
335
336 if tmp.len() != 3 {
337 println!("kill command takes the pid and a signal number in parameter!");
338 println!("example: kill 1254 9");
339 } else {
340 let Ok(pid) = Pid::from_str(tmp[1]) else {
341 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
342 return false;
343 };
344 let Ok(signal) = usize::from_str(tmp[2]) else {
345 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
346 return false;
347 };
348 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
349 eprintln!(
350 "No signal matching {signal}. Use the `signals` command to get the \
351 list of signals.",
352 );
353 return false;
354 };
355
356 match sys {
357 Ok(sys) => match sys.process(pid) {
358 Some(p) => {
359 if let Some(res) = p.kill_with(*signal) {
360 println!("kill: {res}");
361 } else {
362 eprintln!("kill: signal not supported on this platform");
363 }
364 }
365 None => {
366 eprintln!("pid not found");
367 }
368 },
369 Err(error) => {
370 println!("System information cannot be retrieved: {error}");
371 }
372 }
373 }
374 }
375 "disks" => match disks {
376 Ok(disks) => {
377 for disk in disks {
378 println!("{disk:?}");
379 }
380 }
381 Err(error) => {
382 println!("Disks information cannot be retrieved: {error}");
383 }
384 },
385 "users" => match users {
386 Ok(users) => {
387 for user in users {
388 println!("{:?} => {:?}", user.name(), user.groups());
389 }
390 }
391 Err(error) => {
392 println!("Users information cannot be retrieved: {error}");
393 }
394 },
395 "groups" => match Groups::new_with_refreshed_list() {
396 Ok(groups) => {
397 for group in &groups {
398 println!("{group:?}");
399 }
400 }
401 Err(error) => {
402 println!("Groups information cannot be retrieved: {error}");
403 }
404 },
405 "boot_time" => match System::boot_time() {
406 Ok(boot_time) => println!("{boot_time} seconds"),
407 Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
408 },
409 "uptime" => match System::uptime() {
410 Ok(up) => {
411 let mut uptime = up;
412 let days = uptime / 86400;
413 uptime -= days * 86400;
414 let hours = uptime / 3600;
415 uptime -= hours * 3600;
416 let minutes = uptime / 60;
417 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
418 }
419 Err(error) => eprintln!("Failed to get `uptime`: {error}"),
420 },
421 x if x.starts_with("refresh") => {
422 if x == "refresh" {
423 match sys {
424 Ok(sys) => {
425 println!("Getting processes' information...");
426 sys.refresh_all();
427 println!("Done.");
428 }
429 Err(error) => {
430 println!("System information cannot be retrieved: {error}");
431 }
432 }
433 } else if x.starts_with("refresh ") {
434 println!("Getting process' information...");
435 if let Some(pid) = x
436 .split(' ')
437 .filter_map(|pid| pid.parse().ok())
438 .take(1)
439 .next()
440 {
441 match sys {
442 Ok(sys) => {
443 if sys.refresh_processes_specifics(
444 sysinfo::ProcessesToUpdate::Some(&[pid]),
445 true,
446 ProcessRefreshKind::everything(),
447 ) != 0
448 {
449 println!("Process `{pid}` updated successfully");
450 } else {
451 println!("Process `{pid}` couldn't be updated...");
452 }
453 }
454 Err(error) => {
455 println!("System information cannot be retrieved: {error}");
456 }
457 }
458 } else {
459 println!("Invalid [pid] received...");
460 }
461 } else {
462 println!(
463 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
464 list.",
465 );
466 }
467 }
468 "pid" => {
469 println!(
470 "PID: {}",
471 sysinfo::get_current_pid().expect("failed to get PID")
472 );
473 }
474 "system" => {
475 println!(
476 "System name: {}\n\
477 System kernel version: {}\n\
478 System OS version: {}\n\
479 System OS (long) version: {}\n\
480 System host name: {}\n\
481 System kernel: {}",
482 System::name().unwrap_or_else(|_| "<unknown>".to_owned()),
483 System::kernel_version().unwrap_or_else(|_| "<unknown>".to_owned()),
484 System::os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
485 System::long_os_version().unwrap_or_else(|_| "<unknown>".to_owned()),
486 System::host_name().unwrap_or_else(|_| "<unknown>".to_owned()),
487 System::kernel_long_version().unwrap_or_else(|_| "<unknown>".to_owned()),
488 );
489 }
490 "motherboard" => match Motherboard::new() {
491 Ok(m) => println!("{m:#?}"),
492 Err(error) => println!("Cannot retrieve motherboard information: {error:?}"),
493 },
494 "product" => {
495 println!("{:#?}", Product);
496 }
497 e => {
498 println!(
499 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
500 list.",
501 );
502 }
503 }
504 false
505}Sourcepub fn open_files_limit() -> Result<usize, Error>
pub fn open_files_limit() -> Result<usize, Error>
Returns the (default) maximum number of open files for a process.
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("Max open files: {:?}", System::open_files_limit());