Expand description
§sysinfo

sysinfo is a crate used to get a system’s information.
§Supported OSes
It currently supports the following OSes (alphabetically sorted):
- Android
- FreeBSD
- NetBSD
- iOS
- Linux
- macOS
- Raspberry Pi
- Windows
You can still compile and use sysinfo on non-supported OSes, it’ll simply do nothing.
The minimum-supported version of rustc is 1.95.
§Usage
If you want to migrate from an older version, don’t hesitate to take a look at the CHANGELOG and at the migration guide.
⚠️ Before any attempt to read the different structs’ information, you need to update them to get up-to-date information because for most of them, it works on diff between the current value and the old one.
Which is why, it’s much better to keep the same instance of System around instead of
recreating it multiple times.
You have an example into the examples folder. You can run it with cargo run --example simple.
Otherwise, here is a little code sample:
use sysinfo::{
Components, Disks, Networks, System,
};
// Please note that we use "new_all" to ensure that all lists of
// CPUs and processes are filled!
println!("=> system:");
// 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());
if let Ok(mut sys) = System::new_all() {
// First we update all information of our `System` struct.
sys.refresh_all();
// 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());
// 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:");
if let Ok(disks) = Disks::new_with_refreshed_list() {
for disk in &disks {
println!("{disk:?}");
}
}
// Network interfaces name, total data received and total data transmitted:
if let Ok(networks) = Networks::new_with_refreshed_list() {
println!("=> networks:");
for (interface_name, data) in &networks {
println!(
"{}: {} B (down) / {} B (up)",
interface_name.display(),
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:
if let Ok(components) = Components::new_with_refreshed_list() {
println!("=> components:");
for component in &components {
println!("{component:?}");
}
}Please remember that to have some up-to-date information, you need to call the equivalent
refresh method. For example, for the CPU usage:
use sysinfo::System;
let Ok(mut sys) = System::new() else { return };
loop {
sys.refresh_cpu_usage(); // Refreshing CPU usage.
for cpu in sys.cpus() {
print!("{}% ", cpu.usage());
}
// Sleeping to let time for the system to run for long
// enough to have useful information.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
}The multithread feature (disabled by default) enables sysinfo to use more than
one thread to query information. It gives a performance boost, however, this can increase
the memory usage on some platforms (macOS for example).
§Good practice / Performance tips
Most of the time, you don’t want all information provided by sysinfo but just a subset of it.
In this case, it’s recommended to use refresh_specifics(...) methods with only what you need
to have much better performance.
Another issue frequently encountered: unless you know what you’re doing, it’s almost all the
time better to instantiate the System struct once and use this one instance through your
program. The reason is because a lot of information needs a previous measure to be computed
(the CPU usage for example). Another example why it’s much better: in case you want to list
all running processes, sysinfo needs to allocate all memory for the Process struct list,
which takes extra time on the first run.
§Running on Raspberry Pi
It’ll be difficult to build on Raspberry Pi. A good way-around is to cross-build, then send the executable to your Raspberry Pi.
First install the arm toolchain, for example on Ubuntu:
> sudo apt-get install gcc-arm-linux-gnueabihfThen configure cargo to use the corresponding toolchain:
cat << EOF > ~/.cargo/config
[target.armv7-unknown-linux-gnueabihf]
linker = "arm-linux-gnueabihf-gcc"
EOFFinally, cross compile:
rustup target add armv7-unknown-linux-gnueabihf
cargo build --target=armv7-unknown-linux-gnueabihf§Linux on Docker & Windows Subsystem for Linux (WSL)
Virtual Linux systems, such as those run through Docker and Windows Subsystem for Linux (WSL), do
not receive host hardware information via /sys/class/hwmon or /sys/class/thermal. As such,
querying for components may return no results (or unexpected results) when using this library on
virtual systems.
§Use in binaries running inside the macOS or iOS Sandbox/stores
Apple has restrictions as to which APIs can be linked into binaries that are distributed through the app store.
By default, sysinfo is not compatible with these restrictions. You can use the apple-app-store
feature flag to disable the Apple prohibited features. This also enables the apple-sandbox feature.
In the case of applications using the sandbox outside of the app store, the apple-sandbox feature
can be used alone to avoid causing policy violations at runtime.
§How it works
I wrote a blog post you can find here which explains how sysinfo extracts information
on the different systems.
§Running tests
Because we’re looking at system information, some tests have a better chance to succeed when there is a limited number of parallel running tests. To ensure they all pass, use:
cargo test -- --test-threads=1§C interface
It’s possible to use this crate directly from C. Take a look at the Makefile and at the
examples/simple.c file.
To build the C example, just run:
> make
> ./simple
# If needed:
> LD_LIBRARY_PATH=target/debug/ ./simple§Benchmarks
You can run the benchmarks locally with rust nightly by doing:
> cargo bench§Donations
If you appreciate my work and want to support me, you can do it with github sponsors or with patreon.
With the serde feature enabled, you can then serialize sysinfo types. Let’s see an example with serde_json:
use sysinfo::System;
if let Ok(mut sys) = System::new_all() {
// First we update all information of our `System` struct.
sys.refresh_all();
println!("{}", serde_json::to_string(&sys).unwrap());
}Structs§
- CGroup
Limits - Contains memory limits for a cgroup.
- Component
- Getting a component temperature information.
- Components
- Interacting with components.
- Cpu
- Contains all the methods of the
Cpustruct. - CpuRefresh
Kind - Used to determine what you want to refresh specifically on the
Cputype. - Disk
- Struct containing a disk information.
- Disk
Refresh Kind - Used to determine what you want to refresh specifically on the
Disktype. - Disk
Usage - Type containing read and written bytes.
- Disks
- Disks interface.
- Gid
- A group id wrapping a platform specific type.
- Gpu
- Type containing GPU information.
- Gpus
- Type containing GPU information.
- Group
- Type containing group information.
- Groups
- Interacting with groups.
- IpNetwork
- IP networks address for network interface.
- LoadAvg
- A struct representing system load average value.
- MacAddr
- MAC address for network interface.
- Memory
Refresh Kind - Used to determine which memory you want to refresh specifically.
- Motherboard
- This type allows to retrieve motherboard-related information.
- Network
Data - Getting volume of received and transmitted data.
- Networks
- Interacting with network interfaces.
- PCI
- A PCI (Peripheral Component Interconnect) is an architecture used to identify and manage hardware devices.
- Pid
- Process ID.
- Process
- Struct containing information of a process.
- Process
Refresh Kind - Used to determine what you want to refresh specifically on the
Processtype. - Product
- This type allows to retrieve product-related information.
- Refresh
Kind - Used to determine what you want to refresh specifically on the
Systemtype. - System
- Type containing system’s information such as processes, memory and CPU.
- Uid
- A user id wrapping a platform specific type.
- User
- Type containing user information.
- Users
- Interacting with users.
Enums§
- Disk
Kind - Enum containing the different supported kinds of disks.
- Error
- Error type covering the main errors which can happen when querying system information.
- Interface
Operational State - The operational state of some interface based on
IfOperStatusfrom RFC2863. - IpNetwork
From StrError - Error type returned from
MacAddr::from_strimplementation. - Kill
Error - Enum describing possible
Process::kill_and_waiterrors. - MacAddr
From StrError - Error type returned from
MacAddr::from_strimplementation. - Process
Status - Enum describing the different status of a process.
- Processes
ToUpdate - This enum allows you to specify if you want all processes to be updated or just some of them.
- Signal
- An enum representing signals on UNIX-like systems.
- Thread
Kind - Enum describing the different kind of threads.
- Update
Kind - This enum allows you to specify when you want the related information to be updated.
Constants§
- MINIMUM_
CPU_ UPDATE_ INTERVAL - This is the minimum interval time used internally by
sysinfoto refresh the CPU time. - SUPPORTED_
SIGNALS - Returns the list of the supported signals on this system (used by
Process::kill_with).
Functions§
- get_
current_ pid - Returns the pid for the current process.