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;
if sysinfo::IS_SUPPORTED_SYSTEM {
println!("System: {:?}", System::new_all());
} else {
println!("This OS isn't supported (yet?).");
}Implementations§
Source§impl System
impl System
Sourcepub fn new() -> Self
pub fn new() -> Self
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 s = System::new();Sourcepub fn new_all() -> Self
pub fn new_all() -> Self
Creates a new System instance with everything loaded.
It is an equivalent of System::new_with_specifics(RefreshKind::everything()).
use sysinfo::System;
let s = System::new_all();Examples found in repository?
350fn main() {
351 println!("Getting system information...");
352 let mut system = System::new_all();
353 let mut networks = Networks::new_with_refreshed_list();
354 let mut disks = Disks::new_with_refreshed_list();
355 let mut components = Components::new_with_refreshed_list();
356 let mut users = Users::new_with_refreshed_list();
357
358 println!("Done.");
359 let t_stin = io::stdin();
360 let mut stin = t_stin.lock();
361 let mut done = false;
362
363 println!("To get the commands' list, enter 'help'.");
364 while !done {
365 let mut input = String::new();
366 write!(&mut io::stdout(), "> ");
367 io::stdout().flush();
368
369 stin.read_line(&mut input);
370 if input.is_empty() {
371 // The string is empty, meaning there is no '\n', meaning
372 // that the user used CTRL+D so we can just quit!
373 println!("\nLeaving, bye!");
374 break;
375 }
376 if (&input as &str).ends_with('\n') {
377 input.pop();
378 }
379 done = interpret_input(
380 input.as_ref(),
381 &mut system,
382 &mut networks,
383 &mut disks,
384 &mut components,
385 &mut users,
386 );
387 }
388}Sourcepub fn new_with_specifics(refreshes: RefreshKind) -> Self
pub fn new_with_specifics(refreshes: RefreshKind) -> Self
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.
let 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};
let 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;
let mut s = System::new();
s.refresh_all();Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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;
let 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};
let 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_cpu_usage()).
use sysinfo::System;
let mut s = System::new_all();
// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh 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;
let 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};
let 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;
let mut s = System::new_all();
s.refresh_cpu_all();Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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};
let 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)
);⚠️ 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, sysinfo keeps the stat files open by default. You can change this behaviour
by using set_open_files_limit.
⚠️ 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};
let mut s = System::new_all();
s.refresh_processes(ProcessesToUpdate::All, true);Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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.
⚠️ On Linux, sysinfo keeps the stat files open by default. You can change this behaviour
by using set_open_files_limit.
use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System};
let mut s = System::new_all();
s.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::everything(),
);Sourcepub fn processes(&self) -> &HashMap<Pid, Process>
pub fn processes(&self) -> &HashMap<Pid, Process>
Returns the process list.
use sysinfo::System;
let s = System::new_all();
for (pid, process) in s.processes() {
println!("{} {:?}", pid, process.name());
}Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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};
let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
println!("{:?}", process.name());
}Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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;
let s = System::new_all();
for process in s.processes_by_name("htop".as_ref()) {
println!("{} {:?}", process.pid(), process.name());
}Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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;
let 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};
let 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?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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};
let 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.cpu_usage());
}Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn total_memory(&self) -> u64
pub fn total_memory(&self) -> u64
Returns the RAM size in bytes.
use sysinfo::System;
let 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?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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;
let 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 and FreeBSD don’t report “available” memory so System::free_memory
returns the same value as this method.
use sysinfo::System;
let s = System::new_all();
println!("{} bytes", s.available_memory());Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn used_memory(&self) -> u64
pub fn used_memory(&self) -> u64
Returns the amount of used RAM in bytes.
use sysinfo::System;
let s = System::new_all();
println!("{} bytes", s.used_memory());Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn total_swap(&self) -> u64
pub fn total_swap(&self) -> u64
Returns the SWAP size in bytes.
use sysinfo::System;
let s = System::new_all();
println!("{} bytes", s.total_swap());Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn free_swap(&self) -> u64
pub fn free_swap(&self) -> u64
Returns the amount of free SWAP in bytes.
use sysinfo::System;
let 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;
let s = System::new_all();
println!("{} bytes", s.used_swap());Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn cgroup_limits(&self) -> Option<CGroupLimits>
pub fn cgroup_limits(&self) -> Option<CGroupLimits>
Retrieves the limits for the current cgroup (if any), otherwise it returns None.
This information is computed every time the method is called.
⚠️ You need to have run refresh_memory at least once before
calling this method.
⚠️ This method is only implemented for Linux. It always returns None for all other
systems.
use sysinfo::System;
let s = System::new_all();
println!("limits: {:?}", s.cgroup_limits());Sourcepub fn uptime() -> u64
pub fn uptime() -> u64
Returns system uptime (in seconds).
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("System running since {} seconds", System::uptime());Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn boot_time() -> u64
pub fn boot_time() -> u64
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;
println!("System booted at {} seconds", System::boot_time());Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn load_average() -> LoadAvg
pub fn load_average() -> LoadAvg
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;
let load_avg = System::load_average();
println!(
"one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
load_avg.one,
load_avg.five,
load_avg.fifteen,
);Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn name() -> Option<String>
pub fn name() -> Option<String>
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?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn kernel_version() -> Option<String>
pub fn kernel_version() -> Option<String>
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?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn os_version() -> Option<String>
pub fn os_version() -> Option<String>
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?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn long_os_version() -> Option<String>
pub fn long_os_version() -> Option<String>
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?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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() -> String
pub fn kernel_long_version() -> String
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?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn host_name() -> Option<String>
pub fn host_name() -> Option<String>
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?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}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() -> Option<usize>
pub fn physical_core_count() -> Option<usize>
Returns the number of physical cores on the CPU or None if it couldn’t get it.
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;
let s = System::new();
println!("{:?}", System::physical_core_count());Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Sourcepub fn open_files_limit() -> Option<usize>
pub fn open_files_limit() -> Option<usize>
Returns the (default) maximum number of open files for a process.
Returns None if it failed retrieving the information or if the current system is not
supported.
Important: this information is computed every time this function is called.
use sysinfo::System;
println!("Max open files: {:?}", System::open_files_limit());