• Stars
    star
    1,495
  • Rank 31,403 (Top 0.7 %)
  • Language
    Rust
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Cross-platform library to fetch system information

sysinfo

sysinfo is a crate used to get a system's information.

Supported OSes

It currently supports the following OSes (alphabetically sorted):

  • Android
  • FreeBSD
  • iOS
  • Linux
  • macOS
  • Raspberry Pi
  • Windows

You can still use sysinfo on non-supported OSes, it'll simply do nothing and always return empty values. You can check in your program directly if an OS is supported by checking the [SystemExt::IS_SUPPORTED] constant.

The minimum-supported version of rustc is 1.59.

Usage

⚠️ 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::{NetworkExt, NetworksExt, ProcessExt, System, SystemExt};

// Please note that we use "new_all" to ensure that all list of
// components, network interfaces, disks and users are already
// filled!
let mut sys = System::new_all();

// First we update all information of our `System` struct.
sys.refresh_all();

// We display all disks' information:
println!("=> disks:");
for disk in sys.disks().iter() {
    println!("{:?}", disk);
}

// Network interfaces name, data received and data transmitted:
println!("=> networks:");
for (interface_name, data) in sys.networks() {
    println!("{}: {}/{} B", interface_name, data.received(), data.transmitted());
}

// Components temperature:
println!("=> components:");
for component in sys.components() {
    println!("{:?}", component);
}

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:             {:?}", sys.name());
println!("System kernel version:   {:?}", sys.kernel_version());
println!("System OS version:       {:?}", sys.os_version());
println!("System host name:        {:?}", sys.host_name());

// Number of CPUs:
println!("NB CPUs: {}", sys.cpus().len());

// Display processes ID, name na disk usage:
for (pid, process) in sys.processes() {
    println!("[{}] {} {:?}", pid, process.name(), process.disk_usage());
}

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::{CpuExt, System, SystemExt};

let mut sys = System::new();

loop {
    sys.refresh_cpu(); // Refreshing CPU information.
    for cpu in sys.cpus() {
        print!("{}% ", cpu.cpu_usage());
    }
    // Sleeping for 500 ms to let time for the system to run for long
    // enough to have useful information.
    std::thread::sleep(std::time::Duration::from_millis(500));
}

By default, sysinfo uses multiple threads. However, this can increase the memory usage on some platforms (macOS for example). The behavior can be disabled by setting default-features = false in Cargo.toml (which disables the multithread cargo feature).

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 issues 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 quite some time on the first run.

If your program needs to use a lot of file descriptors, you'd better use:

sysinfo::set_open_files_limit(0);

as sysinfo keeps a number of file descriptors open to have better performance on some targets when refreshing processes.

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-multilib-arm-linux-gnueabihf

Then configure cargo to use the corresponding toolchain:

cat << EOF > ~/.cargo/config
[target.armv7-unknown-linux-gnueabihf]
linker = "arm-linux-gnueabihf-gcc"
EOF

Finally, 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.

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/release/ ./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.

More Repositories

1

process-viewer

A process viewer GUI in rust
Rust
351
star
2

rust-GSL

A GSL (the GNU Scientific Library) binding for Rust
Rust
175
star
3

tuto-rust-fr

Un tutoriel pour apprendre Rust
Shell
117
star
4

doc-comment

Write doc comments from macros
Rust
95
star
5

minifier-rs

Minifier tool/lib for JS/CSS/JSON files
Rust
81
star
6

rust-fmod

A rust binding for the FMOD library
Rust
63
star
7

systemd-manager

A systemd service manager written in Rust with the GTK-rs wrapper and direct integration with dbus
Rust
47
star
8

rustc-tools

Some internal rustc tools made accessible
Rust
41
star
9

rust-music-player

A little music player in rust with rsfml and rfmod
Rust
25
star
10

csv-parser

A CSV parser written in Rust with nom
Rust
24
star
11

c_vec-rs

Structures to wrap C arrays
Rust
18
star
12

this-week-in-rust-docs

CSS
14
star
13

mp3-metadata

mp3 metadata parser in rust
Rust
12
star
14

browser-UI-test

small JS framework to easily provide UI screenshot-based tests
JavaScript
12
star
15

rustdoc-stripper

rustdoc-stripper is a tool used to edit/remove rustdoc comments from your code
Rust
12
star
16

html-diff-rs

Rust
7
star
17

rust-toy-game

Rust
7
star
18

ban-ssh-ips

Little script to read failed auths and ban their IPs
Python
5
star
19

howto-linux-kernel

Tutorials to discover how to do some stuff on linux kernel
4
star
20

audio-video-metadata

A crate to parse audio and video metadatas
Rust
4
star
21

ObjectFactory

Object Factory example using C++11
C++
3
star
22

va_list-rs

Rust
3
star
23

Wrapper-RS232-COM-PORT

A class which handles RS232 / COM port links. Works on Windows and Linux.
C++
3
star
24

libpostal-rs

Rust
3
star
25

video-metadata-rs

DEPRECATED. Take a look to https://github.com/GuillaumeGomez/audio-video-metadata
Rust
3
star
26

rustc-tools-example

Example for rustc-tools using cargo
Rust
3
star
27

tetrisJS

A simple Tetris in JS
JavaScript
2
star
28

conference-talks

Talks I made for a few different conferences
JavaScript
2
star
29

HTTP-Sender

A little HTTP request sender in rust
Rust
2
star
30

rust-clean

A little temporary emacs file cleaner in rust
Rust
2
star
31

wire-drawer

A little wire drawer
Rust
2
star
32

android_database-list_example

A little database and list example for android
Java
2
star
33

file-explorer-3D

It is a file explorer in 3D, made with SDL2 and platform independant.
C++
2
star
34

TODO-list

My list of TODO work
2
star
35

stripper-interface

This is the library used by rustdoc-stripper and gir to generate comments files
Rust
1
star
36

git-tips

1
star
37

macro-utils

Rust
1
star
38

merge-bot

Python
1
star
39

Android-File-explorer

A file explorer on android
Java
1
star
40

c_str-rs

Old Rust c_str module
Rust
1
star
41

string-extension

Useful template file to make string's operations easier
C++
1
star