### Build and run C example Source: https://docs.rs/sysinfo/latest/sysinfo/index.html Compile the C interface example and execute the resulting binary. ```bash > make > ./simple # If needed: > LD_LIBRARY_PATH=target/debug/ ./simple ``` -------------------------------- ### Main Loop Example Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Networks.html Example of integrating Networks into a command-line interface loop. ```rust 352fn main() { 353 println!("Getting system information..."); 354 let mut system = System::new_all(); 355 let mut networks = Networks::new_with_refreshed_list(); 356 let mut disks = Disks::new_with_refreshed_list(); 357 let mut components = Components::new_with_refreshed_list(); 358 let mut users = Users::new_with_refreshed_list(); 359 360 println!("Done."); 361 let t_stin = io::stdin(); 362 let mut stin = t_stin.lock(); 363 let mut done = false; 364 365 println!("To get the commands' list, enter 'help'."); 366 while !done { 367 let mut input = String::new(); 368 write!(&mut io::stdout(), "> "); 369 io::stdout().flush(); 370 371 stin.read_line(&mut input); 372 if input.is_empty() { 373 // The string is empty, meaning there is no '\n', meaning 374 // that the user used CTRL+D so we can just quit! 375 println!("\nLeaving, bye!"); 376 break; 377 } 378 if (&input as &str).ends_with('\n') { 379 input.pop(); 380 } 381 done = interpret_input( 382 input.as_ref(), 383 &mut system, 384 &mut networks, 385 &mut disks, 386 &mut components, 387 &mut users, 388 ); 389 } 390} ``` -------------------------------- ### System Metrics and Utilities Source: https://docs.rs/sysinfo/latest/sysinfo/struct.NetworkData.html Examples for retrieving system boot time, uptime, and refreshing process information. ```rust "boot_time" => { println!("{} seconds", System::boot_time()); } "uptime" => { let up = System::uptime(); let mut uptime = up; let days = uptime / 86400; uptime -= days * 86400; let hours = uptime / 3600; uptime -= hours * 3600; let minutes = uptime / 60; println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)"); } x if x.starts_with("refresh") => { if x == "refresh" { println!("Getting processes' information..."); sys.refresh_all(); println!("Done."); } else if x.starts_with("refresh ") { println!("Getting process' information..."); if let Some(pid) = x .split(' ') .filter_map(|pid| pid.parse().ok()) .take(1) .next() { ``` -------------------------------- ### Handle Process command matching Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Process.html Example of matching on command inputs to retrieve motherboard or product information. ```rust 335 "motherboard" => match Motherboard::new() { 336 Some(m) => println!("{m:#?}"), 337 None => println!("No motherboard information available"), 338 }, 339 "product" => { 340 println!("{:#?}", Product); 341 } 342 e => { 343 println!( 344 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \ 345 list.", 346 ); 347 } 348 } 349 false 350} ``` -------------------------------- ### Debug print Product Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Product.html Example of printing the Product struct. ```rust use sysinfo::Product; println!("{:?}", Product); ``` -------------------------------- ### Install ARM toolchain on Ubuntu Source: https://docs.rs/sysinfo/latest/sysinfo/index.html Install the necessary cross-compilation toolchain for Raspberry Pi targets. ```bash > sudo apt-get install gcc-multilib-arm-linux-gnueabihf ``` -------------------------------- ### Interpret Input Example Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Networks.html Example of handling network refresh commands within an input interpretation function. ```rust 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 } ``` -------------------------------- ### pub fn start_time(&self) -> u64 Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Process.html Returns the time when the process was started, measured in seconds from the Unix epoch. ```APIDOC ## pub fn start_time(&self) -> u64 ### Description Returns the time where the process was started (in seconds) from epoch. ### Returns - **u64** - The start time in seconds since epoch. ``` -------------------------------- ### Retrieve Process Start Time Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Process.html Returns the process start time in seconds since the epoch. ```rust use sysinfo::{Pid, System}; let s = System::new_all(); if let Some(process) = s.process(Pid::from(1337)) { println!("Started at {} seconds", process.start_time()); } ``` -------------------------------- ### Access DiskUsage metrics Source: https://docs.rs/sysinfo/latest/sysinfo/struct.DiskUsage.html Example showing how to retrieve and print disk usage statistics for active processes and system disks. ```rust use sysinfo::{Disks, System}; let s = System::new_all(); for (pid, process) in s.processes() { let disk_usage = process.disk_usage(); println!("[{}] read bytes : new/total => {}/{} B", pid, disk_usage.read_bytes, disk_usage.total_read_bytes, ); println!("[{}] written bytes: new/total => {}/{} B", pid, disk_usage.written_bytes, disk_usage.total_written_bytes, ); } let disks = Disks::new_with_refreshed_list(); for disk in disks.list() { println!("[{:?}] disk usage: {:?}", disk.name(), disk.usage()); } ``` -------------------------------- ### pub fn cmd(&self) -> &[OsString] Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Process.html Returns the command line arguments used to start the process. Note that on Windows, administrator privileges may be required to access this information. ```APIDOC ## pub fn cmd(&self) -> &[OsString] ### Description Returns the command line arguments of the process. ### Example ```rust use sysinfo::{Pid, System}; let s = System::new_all(); if let Some(process) = s.process(Pid::from(1337)) { println!("{:?}", process.cmd()); } ``` ``` -------------------------------- ### Query Process and CPU Metadata Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Cpu.html Examples for listing processes, checking CPU frequency, vendor ID, brand, and system load averages. ```rust "all" => { for (pid, proc_) in sys.processes() { println!( "{}:{} status={:?}", pid, proc_.name().to_string_lossy(), proc_.status() ); } } "frequency" => { for cpu in sys.cpus() { println!("[{}] {} MHz", cpu.name(), cpu.frequency()); } } "vendor_id" => { println!("vendor ID: {}", sys.cpus()[0].vendor_id()); } "brand" => { println!("brand: {}", sys.cpus()[0].brand()); } "load_avg" => { let load_avg = System::load_average(); println!("one minute : {}%", load_avg.one); println!("five minutes : {}%", load_avg.five); println!("fifteen minutes: {}%", load_avg.fifteen); } ``` -------------------------------- ### System Information Input Handler Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Process.html Example implementation of a command-line input handler for system monitoring and process signal listing. ```rust 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); ``` -------------------------------- ### Interpret system input commands Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Networks.html Example function demonstrating how to refresh network and system data based on user input. ```rust 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() { ``` -------------------------------- ### Interpret System Input Commands Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Cpu.html A command-line interface example showing how to interact with CPU data, including frequency, vendor ID, and brand information. ```rust 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(); ``` -------------------------------- ### Example Code Block Source: https://docs.rs/sysinfo/latest/sysinfo/struct.NetworkData.html A code snippet found in the source documentation. ```rust 344 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \ 345 list.", 346 ); 347 } 348 } 349 false 350} ``` -------------------------------- ### Interpreting System Input Source: https://docs.rs/sysinfo/latest/sysinfo/struct.User.html Example of handling user input to refresh system components including users. ```rust 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 ") => { ``` -------------------------------- ### Process and Network Data Retrieval Source: https://docs.rs/sysinfo/latest/sysinfo/struct.NetworkData.html Examples of querying process details, network interface statistics, and system-wide metrics. ```rust match sys.process(pid) { Some(p) => { println!("{:?}", *p); println!( "Files open/limit: {:?}/{:?}", p.open_files(), p.open_files_limit(), ); } None => { println!("pid \"{pid:?}\" not found"); } } } else { let proc_name = tmp[1]; for proc_ in sys.processes_by_name(proc_name.as_ref()) { println!("==== {} ====", proc_.name().to_string_lossy()); println!("{proc_:?}"); } } } "temperature" => { for component in components.iter() { println!("{component:?}"); } } "network" => { for (interface_name, data) in networks.iter() { println!( "\ {interface_name}: operational state {} ether {} input data (new / total): {} / {} B output data (new / total): {} / {} B", data.operational_state(), data.mac_address(), data.received(), data.total_received(), data.transmitted(), data.total_transmitted(), ); } } ``` -------------------------------- ### Retrieving File System Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Disk.html Get the file system type of the disk. ```rust use sysinfo::Disks; let disks = Disks::new_with_refreshed_list(); for disk in disks.list() { println!("[{:?}] {:?}", disk.name(), disk.file_system()); } ``` -------------------------------- ### Retrieve System Load Average Source: https://docs.rs/sysinfo/latest/sysinfo/struct.LoadAvg.html Example usage of System::load_average to access and print the load metrics. ```rust 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, ); ``` -------------------------------- ### Configure Process Refresh Specifics Source: https://docs.rs/sysinfo/latest/sysinfo/struct.ProcessRefreshKind.html Example demonstrating how to exclude CPU information from process refreshes to optimize performance. ```Rust use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System}; let mut system = System::new(); // We don't want to update the CPU information. system.refresh_processes_specifics( ProcessesToUpdate::All, true, ProcessRefreshKind::everything().without_cpu(), ); for (_, proc_) in system.processes() { // We use a `==` comparison on float only because we know it's set to 0 here. assert_eq!(proc_.cpu_usage(), 0.); } ``` -------------------------------- ### Configure Process Refresh with UpdateKind Source: https://docs.rs/sysinfo/latest/sysinfo/enum.UpdateKind.html Example showing how to use UpdateKind to conditionally refresh process executable information. ```rust use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System, UpdateKind}; let mut system = System::new(); system.refresh_processes_specifics( ProcessesToUpdate::All, true, ProcessRefreshKind::nothing().with_exe(UpdateKind::OnlyIfNotSet), ); ``` -------------------------------- ### Retrieve CPU Brand Information Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Cpu.html Demonstrates how to initialize a System instance with specific CPU refresh settings and iterate through CPUs to print their brand names. ```rust use sysinfo::{System, RefreshKind, CpuRefreshKind}; let s = System::new_with_specifics( RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()), ); for cpu in s.cpus() { println!("{}", cpu.brand()); } ``` -------------------------------- ### Retrieving Disk Kind Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Disk.html Get the type of the disk. ```rust use sysinfo::Disks; let disks = Disks::new_with_refreshed_list(); for disk in disks.list() { println!("[{:?}] {:?}", disk.name(), disk.kind()); } ``` -------------------------------- ### Process and System Information Retrieval Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Cpu.html Demonstrates how to query process details, system temperature, network interface statistics, and system uptime. ```rust println!("{:?}", *p); println!( "Files open/limit: {:?}/{:?}", p.open_files(), p.open_files_limit(), ); } None => { println!("pid \"{pid:?}\" not found"); } } } else { let proc_name = tmp[1]; for proc_ in sys.processes_by_name(proc_name.as_ref()) { println!("==== {} ====", proc_.name().to_string_lossy()); println!("{proc_:?}"); } } } "temperature" => { for component in components.iter() { println!("{component:?}"); } } "network" => { for (interface_name, data) in networks.iter() { println!( "\ {interface_name}: operational state {} ether {} input data (new / total): {} / {} B output data (new / total): {} / {} B", data.operational_state(), data.mac_address(), data.received(), data.total_received(), data.transmitted(), data.total_transmitted(), ); } } "show" => { println!("'show' command expects a pid number or a process name"); } ``` -------------------------------- ### Retrieving Disk Name Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Disk.html Get the name of the disk as an OsStr. ```rust use sysinfo::Disks; let disks = Disks::new_with_refreshed_list(); for disk in disks.list() { println!("{:?}", disk.name()); } ``` -------------------------------- ### Initialize Motherboard Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Motherboard.html Create a new instance of the Motherboard struct to access system information. ```rust use sysinfo::Motherboard; if let Some(m) = Motherboard::new() { println!("{m:?}"); } ``` -------------------------------- ### Retrieving Total Space Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Disk.html Get the total capacity of the disk in bytes. ```rust use sysinfo::Disks; let disks = Disks::new_with_refreshed_list(); for disk in disks.list() { println!("[{:?}] {}B", disk.name(), disk.total_space()); } ``` -------------------------------- ### Retrieve and Display System Information Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Cpu.html Demonstrates how to fetch and print various system details including OS version, kernel, and host name. ```rust if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 { println!("Process `{pid}` updated successfully"); } else { println!("Process `{pid}` couldn't be updated..."); } } else { println!("Invalid [pid] received..."); } } else { println!( "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \ list.", ); } } "pid" => { println!( "PID: {}", sysinfo::get_current_pid().expect("failed to get PID") ); } "system" => { println!( "System name: {}\n\ System kernel version: {}\n\ System OS version: {}\n\ System OS (long) version: {}\n\ System host name: {}\n\ System kernel: {}", System::name().unwrap_or_else(|| "".to_owned()), System::kernel_version().unwrap_or_else(|| "".to_owned()), System::os_version().unwrap_or_else(|| "".to_owned()), System::long_os_version().unwrap_or_else(|| "".to_owned()), System::host_name().unwrap_or_else(|| "".to_owned()), System::kernel_long_version(), ); } "motherboard" => match Motherboard::new() { Some(m) => println!("{m:#?}"), None => println!("No motherboard information available"), }, "product" => { println!("{:#?}", Product); } e => { println!( "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \ list.", ); } } false } ``` -------------------------------- ### Retrieving Mount Point Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Disk.html Get the mount point path of the disk. ```rust use sysinfo::Disks; let disks = Disks::new_with_refreshed_list(); for disk in disks.list() { println!("[{:?}] {:?}", disk.name(), disk.mount_point()); } ``` -------------------------------- ### Initialize and convert Pid Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Pid.html Demonstrates creating a Pid instance and converting it to a u32. ```rust use sysinfo::Pid; // 0's type will be different depending on the platform! let p = Pid::from(0); // For something more "general": let p = Pid::from_u32(0); let i: u32 = p.as_u32(); ``` -------------------------------- ### Get value from HashMap Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Networks.html Returns a reference to the value corresponding to the provided key. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Retrieve CPU Usage Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Cpu.html Demonstrates how to initialize the system with CPU monitoring and retrieve usage percentages. Note that CPU usage requires at least two refresh cycles to calculate a non-zero value. ```rust use sysinfo::{System, RefreshKind, CpuRefreshKind}; 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_all(); for cpu in s.cpus() { println!("{}%", cpu.cpu_usage()); } ``` -------------------------------- ### RefreshKind::cpu Source: https://docs.rs/sysinfo/latest/sysinfo/struct.RefreshKind.html Methods to get, set, or unset the CPU refresh configuration. ```APIDOC ## CPU Refresh Methods ### Methods - `pub fn cpu(&self) -> Option`: Returns the current CPU refresh configuration. - `pub fn with_cpu(self, kind: CpuRefreshKind) -> Self`: Sets the CPU refresh configuration. - `pub fn without_cpu(self) -> Self`: Disables CPU refreshing. ``` -------------------------------- ### RefreshKind::memory Source: https://docs.rs/sysinfo/latest/sysinfo/struct.RefreshKind.html Methods to get, set, or unset the memory refresh configuration. ```APIDOC ## Memory Refresh Methods ### Methods - `pub fn memory(&self) -> Option`: Returns the current memory refresh configuration. - `pub fn with_memory(self, kind: MemoryRefreshKind) -> Self`: Sets the memory refresh configuration. - `pub fn without_memory(self) -> Self`: Disables memory refreshing. ``` -------------------------------- ### Motherboard::new() Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Motherboard.html Creates a new instance of the Motherboard type. Returns None if the information cannot be retrieved or if the platform is not supported (e.g., NetBSD). ```APIDOC ## pub fn new() -> Option ### Description Creates a new instance of the `Motherboard` type. This is the primary entry point for accessing motherboard information. ### Signature `pub fn new() -> Option` ### Returns - **Option** - Returns `Some(Motherboard)` if successful, or `None` if the information is unavailable or the platform is not supported. ### Example ```rust use sysinfo::Motherboard; if let Some(m) = Motherboard::new() { println!("{m:?}"); } ``` ``` -------------------------------- ### Retrieve System Information Source: https://docs.rs/sysinfo/latest/sysinfo/index.html Initializes a System instance and retrieves comprehensive system metrics including memory, OS details, processes, disks, networks, and components. ```rust use sysinfo::{ Components, Disks, Networks, System, }; // Please note that we use "new_all" to ensure that all lists of // CPUs and processes are filled! let mut sys = System::new_all(); // First we update all information of our `System` struct. sys.refresh_all(); println!("=> system:"); // RAM and swap information: println!("total memory: {} bytes", sys.total_memory()); println!("used memory : {} bytes", sys.used_memory()); println!("total swap : {} bytes", sys.total_swap()); println!("used swap : {} bytes", sys.used_swap()); // Display system information: println!("System name: {:?}", System::name()); println!("System kernel version: {:?}", System::kernel_version()); println!("System OS version: {:?}", System::os_version()); println!("System host name: {:?}", System::host_name()); // Number of CPUs: println!("NB CPUs: {}", sys.cpus().len()); // Display processes ID, name and disk usage: for (pid, process) in sys.processes() { println!("[{pid}] {:?} {:?}", process.name(), process.disk_usage()); } // We display all disks' information: println!("=> disks:"); let disks = Disks::new_with_refreshed_list(); for disk in &disks { println!("{disk:?}"); } // Network interfaces name, total data received and total data transmitted: let networks = Networks::new_with_refreshed_list(); println!("=> networks:"); for (interface_name, data) in &networks { println!( "{interface_name}: {} B (down) / {} B (up)", data.total_received(), data.total_transmitted(), ); // If you want the amount of data received/transmitted since last call // to `Networks::refresh`, use `received`/`transmitted`. } // Components temperature: let components = Components::new_with_refreshed_list(); println!("=> components:"); for component in &components { println!("{component:?}"); } ``` -------------------------------- ### RefreshKind::processes Source: https://docs.rs/sysinfo/latest/sysinfo/struct.RefreshKind.html Methods to get, set, or unset the process refresh configuration. ```APIDOC ## Process Refresh Methods ### Methods - `pub fn processes(&self) -> Option`: Returns the current process refresh configuration. - `pub fn with_processes(self, kind: ProcessRefreshKind) -> Self`: Sets the process refresh configuration. - `pub fn without_processes(self) -> Self`: Disables process refreshing. ``` -------------------------------- ### Retrieving Disk Usage Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Disk.html Get the number of bytes read and written by the disk. ```rust use sysinfo::Disks; let disks = Disks::new_with_refreshed_list(); for disk in disks.list() { println!("[{:?}] disk usage: {:?}", disk.name(), disk.usage()); } ``` -------------------------------- ### Query System and Process Information Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Process.html Demonstrates how to iterate through processes, retrieve CPU metrics, and display load averages. ```rust println!("used swap: {: >10} KB", sys.used_swap() / 1_000); } "quit" | "exit" => return true, "all" => { for (pid, proc_) in sys.processes() { println!( "{}:{} status={:?}", pid, proc_.name().to_string_lossy(), proc_.status() ); } } "frequency" => { for cpu in sys.cpus() { println!("[{}] {} MHz", cpu.name(), cpu.frequency()); } } "vendor_id" => { println!("vendor ID: {}", sys.cpus()[0].vendor_id()); } "brand" => { println!("brand: {}", sys.cpus()[0].brand()); } "load_avg" => { let load_avg = System::load_average(); println!("one minute : {}%", load_avg.one); println!("five minutes : {}%", load_avg.five); println!("fifteen minutes: {}%", load_avg.fifteen); } ``` -------------------------------- ### Retrieving Available Space Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Disk.html Get the available free space on the disk in bytes. ```rust use sysinfo::Disks; let disks = Disks::new_with_refreshed_list(); for disk in disks.list() { println!("[{:?}] {}B", disk.name(), disk.available_space()); } ``` -------------------------------- ### Retrieve System Metrics and Process Information Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Process.html These snippets demonstrate how to access CPU, memory, and process data from a System instance. ```rust println!( "number of physical cores: {}", System::physical_core_count() .map(|c| c.to_string()) .unwrap_or_else(|| "Unknown".to_owned()), ); println!("total CPU usage: {}%", sys.global_cpu_usage()); for cpu in sys.cpus() { println!("{cpu:?}"); } ``` ```rust println!("total memory: {: >10} KB", sys.total_memory() / 1_000); println!( "available memory: {: >10} KB", sys.available_memory() / 1_000 ); println!("used memory: {: >10} KB", sys.used_memory() / 1_000); println!("total swap: {: >10} KB", sys.total_swap() / 1_000); println!("used swap: {: >10} KB", sys.used_swap() / 1_000); ``` ```rust for (pid, proc_) in sys.processes() { println!( "{}:{} status={:?}", pid, proc_.name().to_string_lossy(), proc_.status() ); } ``` ```rust for cpu in sys.cpus() { println!("[{}] {} MHz", cpu.name(), cpu.frequency()); } ``` ```rust println!("vendor ID: {}", sys.cpus()[0].vendor_id()); ``` ```rust println!("brand: {}", sys.cpus()[0].brand()); ``` ```rust let load_avg = System::load_average(); println!("one minute : {}%", load_avg.one); println!("five minutes : {}%", load_avg.five); println!("fifteen minutes: {}%", load_avg.fifteen); ``` ```rust for component in components.iter() { println!("{component:?}"); } ``` ```rust for (interface_name, data) in networks.iter() { println!( "\ {interface_name}: operational state {} ether {} input data (new / total): {} / {} B output data (new / total): {} / {} B", data.operational_state(), data.mac_address(), data.received(), data.total_received(), data.transmitted(), data.total_transmitted(), ); } ``` -------------------------------- ### Retrieve System Timing Source: https://docs.rs/sysinfo/latest/sysinfo/struct.NetworkData.html Calculates and displays system boot time and uptime. ```rust "boot_time" => { println!("{} seconds", System::boot_time()); } "uptime" => { let up = System::uptime(); let mut uptime = up; let days = uptime / 86400; uptime -= days * 86400; let hours = uptime / 3600; uptime -= hours * 3600; let minutes = uptime / 60; println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)"); } ``` -------------------------------- ### Retrieve MTU for Interfaces Source: https://docs.rs/sysinfo/latest/sysinfo/struct.NetworkData.html Get the Maximum Transfer Unit (MTU) value for network interfaces. ```rust use sysinfo::Networks; let mut networks = Networks::new_with_refreshed_list(); for (interface_name, network) in &networks { println!("mtu: {}", network.mtu()); } ``` -------------------------------- ### Retrieve total outgoing packets Source: https://docs.rs/sysinfo/latest/sysinfo/struct.NetworkData.html Use total_packets_transmitted to get the cumulative count of outgoing packets. ```rust use sysinfo::Networks; let networks = Networks::new_with_refreshed_list(); for (interface_name, network) in &networks { println!("out: {}", network.total_packets_transmitted()); } ``` -------------------------------- ### Retrieve total incoming packets Source: https://docs.rs/sysinfo/latest/sysinfo/struct.NetworkData.html Use total_packets_received to get the cumulative count of incoming packets. ```rust use sysinfo::Networks; let networks = Networks::new_with_refreshed_list(); for (interface_name, network) in &networks { println!("in: {}", network.total_packets_received()); } ``` -------------------------------- ### List System Resources Source: https://docs.rs/sysinfo/latest/sysinfo/struct.NetworkData.html Iterates through and prints information for disks, users, and groups. ```rust "disks" => { for disk in disks { println!("{disk:?}"); } } "users" => { for user in users { println!("{:?} => {:?}", user.name(), user.groups()); } } "groups" => { for group in Groups::new_with_refreshed_list().list() { println!("{group:?}"); } } ``` -------------------------------- ### Retrieve CPU Frequency Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Cpu.html Demonstrates how to initialize the system with CPU refresh enabled and iterate through CPUs to print their frequency. ```rust use sysinfo::{System, RefreshKind, CpuRefreshKind}; let s = System::new_with_specifics( RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()), ); for cpu in s.cpus() { println!("{}", cpu.frequency()); } ``` -------------------------------- ### Configure Executable Refresh Kind Source: https://docs.rs/sysinfo/latest/sysinfo/struct.ProcessRefreshKind.html Methods to get, set, or disable the executable path refresh kind. ```rust use sysinfo::{ProcessRefreshKind, UpdateKind}; let r = ProcessRefreshKind::nothing(); assert_eq!(r.exe(), UpdateKind::Never); let r = r.with_exe(UpdateKind::OnlyIfNotSet); assert_eq!(r.exe(), UpdateKind::OnlyIfNotSet); let r = r.without_exe(); assert_eq!(r.exe(), UpdateKind::Never); ``` ```rust use sysinfo::{ProcessRefreshKind, UpdateKind}; let r = ProcessRefreshKind::nothing(); assert_eq!(r.exe(), UpdateKind::Never); let r = r.with_exe(UpdateKind::OnlyIfNotSet); assert_eq!(r.exe(), UpdateKind::OnlyIfNotSet); ``` ```rust use sysinfo::{ProcessRefreshKind, UpdateKind}; let r = ProcessRefreshKind::everything(); assert_eq!(r.exe(), UpdateKind::OnlyIfNotSet); let r = r.without_exe(); assert_eq!(r.exe(), UpdateKind::Never); ``` -------------------------------- ### System Information Queries Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Cpu.html Various commands to retrieve system-wide information like disks, users, groups, boot time, and uptime. ```rust "disks" => { for disk in disks { println!("{disk:?}"); } } ``` ```rust "users" => { for user in users { println!("{:?} => {:?}", user.name(), user.groups()); } } ``` ```rust "groups" => { for group in Groups::new_with_refreshed_list().list() { println!("{group:?}"); } } ``` ```rust "boot_time" => { println!("{} seconds", System::boot_time()); } ``` ```rust "uptime" => { let up = System::uptime(); let mut uptime = up; let days = uptime / 86400; uptime -= days * 86400; let hours = uptime / 3600; uptime -= hours * 3600; let minutes = uptime / 60; ``` -------------------------------- ### System Metadata Retrieval Source: https://docs.rs/sysinfo/latest/sysinfo/struct.Process.html Retrieves and prints current PID, system information, motherboard, and product details. ```rust "pid" => { println!( "PID: {}", sysinfo::get_current_pid().expect("failed to get PID") ); } "system" => { println!( "System name: {}\n\ System kernel version: {}\n\ System OS version: {}\n\ System OS (long) version: {}\n\ System host name: {}\n\ System kernel: {}", System::name().unwrap_or_else(|| "".to_owned()), System::kernel_version().unwrap_or_else(|| "".to_owned()), System::os_version().unwrap_or_else(|| "".to_owned()), System::long_os_version().unwrap_or_else(|| "".to_owned()), System::host_name().unwrap_or_else(|| "".to_owned()), System::kernel_long_version(), ); } "motherboard" => match Motherboard::new() { Some(m) => println!("{m:#?}"), None => println!("No motherboard information available"), }, "product" => { println!("{:#?}", Product); } e => { println!( "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \ list.", ); } } false } ```