Git Product home page Git Product logo

sysinfo's Introduction

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 [IS_SUPPORTED_SYSTEM] constant.

The minimum-supported version of rustc is 1.74.

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!
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 na 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:?}");
}

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 mut sys = System::new();

loop {
    sys.refresh_cpu_usage(); // Refreshing CPU usage.
    for cpu in sys.cpus() {
        print!("{}% ", cpu.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);
}

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

sysinfo's People

Contributors

aeyno avatar arctic-alpaca avatar bvaisvil avatar chklauser avatar clementtsang avatar complexspaces avatar daladim avatar darnuria avatar gongzhengyang avatar guillaumegomez avatar jasonozias avatar joriwind avatar kayoch1n avatar lonng avatar lunnova avatar mbikovitsky avatar mjarkk avatar onur avatar patrickelectric avatar picrap avatar poliorcetics avatar roblabla avatar scalar438 avatar shahn avatar shanelillierad avatar softdevca avatar tshepang avatar williamvenner avatar yozhgoor avatar zeenix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sysinfo's Issues

[linux] `get_disks()` does not return any disks with the `/dev/nvm` prefix

This seems to be related to #69 and #70. Those issues address disks missing with the sd prefix, however it seems that some disks have an nvm prefix, rather than sd.

Here is an enumeration of the disks on my machine when running sudo fdisk -l:

Device           Start        End   Sectors   Size Type
/dev/nvme0n1p2    2048    1050623   1048576   512M EFI System
/dev/nvme0n1p6 1050624 1000214527 999163904 476.4G Linux filesystem

And here is the info again but with cat /proc/partitions:

 259        0  500107608 nvme0n1
 259        1     524288 nvme0n1p2
 259        2  499581952 nvme0n1p6

I'll submit a PR to add an OR check for this here next time I get a chance.

Huge cleanup

Linux and Mac code should be separated into their own sub-module. Just avoid code duplication by creating a common module where common code should be put.

Removing warnings from both platforms should be done as well.

Cannot build for armv7 target

Hello,

I was trying to install sysinfo-web on my Raspberry Pi, but the build of sysinfo fails for the armv7 target.

The same errors happen even if I try to build sysinfo directly:

# clone the project
cd /tmp
git clone [email protected]:GuillaumeGomez/sysinfo.git
cd sysinfo

# ensure that the armv7 toolchain is installed
rustup target add armv7-unknown-linux-gnueabihf

# try to build
cargo build --target=armv7-unknown-linux-gnueabihf

Here is the output of the build:

cargo build --target=armv7-unknown-linux-gnueabihf --verbose
       Fresh libc v0.2.34
   Compiling sysinfo v0.3.17 (file:///tmp/sysinfo)
     Running `rustc --crate-name sysinfo src/sysinfo.rs --crate-type rlib --crate-type cdylib --emit=dep-info,link -C debuginfo=2 -C metadata=2493776c0d9bda08 --out-dir /tmp/sysinfo/target/armv7-unknown-linux-gnueabihf/debug/deps --target armv7-unknown-linux-gnueabihf -C linker=arm-linux-gnueabihf-gcc-4.7 -L dependency=/tmp/sysinfo/target/armv7-unknown-linux-gnueabihf/debug/deps -L dependency=/tmp/sysinfo/target/debug/deps --extern libc=/tmp/sysinfo/target/armv7-unknown-linux-gnueabihf/debug/deps/liblibc-ade5f8b28de429dc.rlib`
error[E0308]: mismatched types
  --> src/linux/disk.rs:63:20
   |
63 |         if statvfs(mount_point_cpath.as_ptr() as *const i8, &mut stat) == 0 {
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected u8, found i8
   |
   = note: expected type `*const u8`
              found type `*const i8`

error[E0308]: mismatched types
  --> src/linux/disk.rs:73:22
   |
73 |         total_space: total_space,
   |                      ^^^^^^^^^^^ expected u64, found u32

error[E0308]: mismatched types
  --> src/linux/disk.rs:74:26
   |
74 |         available_space: available_space,
   |                          ^^^^^^^^^^^^^^^ expected u64, found u32

error[E0308]: mismatched types
   --> src/linux/disk.rs:126:24
    |
126 |             if statvfs(mount_point_cpath.as_ptr() as *const i8, &mut stat) == 0 {
    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected u8, found i8
    |
    = note: expected type `*const u8`
               found type `*const i8`

error[E0308]: mismatched types
   --> src/linux/disk.rs:127:40
    |
127 |                 self.available_space = stat.f_bsize * stat.f_bavail;
    |                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected u64, found u32

error: aborting due to 5 previous errors

error: Could not compile `sysinfo`.

Caused by:
  process didn't exit successfully: `rustc --crate-name sysinfo src/sysinfo.rs --crate-type rlib --crate-type cdylib --emit=dep-info,link -C debuginfo=2 -C metadata=2493776c0d9bda08 --out-dir /tmp/sysinfo/target/armv7-unknown-linux-gnueabihf/debug/deps --target armv7-unknown-linux-gnueabihf -C linker=arm-linux-gnueabihf-gcc-4.7 -L dependency=/tmp/sysinfo/target/armv7-unknown-linux-gnueabihf/debug/deps -L dependency=/tmp/sysinfo/target/debug/deps --extern libc=/tmp/sysinfo/target/armv7-unknown-linux-gnueabihf/debug/deps/liblibc-ade5f8b28de429dc.rlib` (exit code: 101)

Do you know if this can be fixed easily?

Thanks.

Linux process names misrepresented

On linux, there are some processes with names like "-:0". These get reported by sysinfo as having name "-", the ":0" part is lost. There is some logic to do this on purpose in linux/system.rs, line 273. What's the rationale for this?

Note that /proc/pid/comm gives the name of the display manager for this, so another different thing. htop shows -:0

Maybe use mac functions for mac target?

Functions such as:

fn proc_pidpath(pid: i32, buf: *mut i8, bufsize: u32) -> i32;
fn proc_name(pid: i32, buf: *mut i8, bufsize: u32) -> i32;

It might give a little performance boost?

Component temperature on macOS

Running the simple example, I'm getting these results for component temperature:

CPU: 0°C (max: 0°C)
Battery: 0°C (max: 0°C)

Other system informations are accurate, there only seems to be a problem with these.
Running on macOS High Sierra 10.13.6 on a 2.2Ghz 2015 15" MacBook Pro.

`Process` is does not implement `Send + Sync` on windows

Hey,
on Linux the Process struct implements Send + Sync, but not on Windows.
We have the following bug report.

After looking into the Process code for Windows, I think that HANDLE is the problem. You probably need to create a pointer wrapper that makes HANDLE SEND + SYNC.

Panics after wake up from suspend

thread '<unnamed>' panicked at 'attempt to subtract with overflow', /home/onur/.cargo/registry/src/github.com-1ecc6299db9ec823/sysinfo-0.3.6/src/linux/system.rs:39

Failing CI for OSX

CI gives:

test system::tests::test_refresh_system ... FAILED
failures:
---- system::tests::test_refresh_system stdout ----
thread 'system::tests::test_refresh_system' panicked at 'assertion failed: sys.get_total_memory() >= sys.get_free_memory()', src/system.rs:21:9
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
stack backtrace:
   0: std::sys::unix::backtrace::tracing::imp::unwind_backtrace
             at libstd/sys/unix/backtrace/tracing/gcc_s.rs:49
   1: std::sys_common::backtrace::print
             at libstd/sys_common/backtrace.rs:71
             at libstd/sys_common/backtrace.rs:59
   2: std::panicking::default_hook::{{closure}}
             at libstd/panicking.rs:211
   3: std::panicking::default_hook
             at libstd/panicking.rs:221
   4: <std::panicking::begin_panic::PanicPayload<A> as core::panic::BoxMeUp>::get
             at libstd/panicking.rs:475
   5: crossbeam_epoch::deferred::Deferred::call::fail
             at /Users/travis/build/rust-lang/rust/src/libstd/panicking.rs:409
   6: sysinfo::system::tests::test_refresh_system
             at src/system.rs:21
   7: sysinfo::__test::TESTS::{{closure}}
             at src/system.rs:16
   8: core::ops::function::FnOnce::call_once
             at /Users/travis/build/rust-lang/rust/src/libcore/ops/function.rs:223
   9: <F as alloc::boxed::FnBox<A>>::call_box
             at libtest/lib.rs:1451
             at /Users/travis/build/rust-lang/rust/src/libcore/ops/function.rs:223
             at /Users/travis/build/rust-lang/rust/src/liballoc/boxed.rs:642
  10: panic_unwind::dwarf::eh::read_encoded_pointer
             at libpanic_unwind/lib.rs:105
failures:
    system::tests::test_refresh_system
test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

Any plans to add an authentication?

Hi! First of all, thanks for the nice tool!

I'd like to ask: are there any plans to add some kind of authentication? (e.g. at least HTTP Basic Auth?)

Menus handling

Instead of the current way to generate menus, I should use Gio::Menu (to have the nice menus in the headbar on OSX for example).

`sysinfo::System::new()` slow?

A simple program creating a sysinfo::System takes several times longer to run (after cargo build --release) than existing unix utilities from the procps suite (~40ms instead of ~14ms):

extern crate sysinfo;
use sysinfo::SystemExt;

fn main()
{
	let mut system = sysinfo::System::new();
}

I haven't done experiments (just observations), so the following analysis is expectation, not known truth:

I wouldn't expect any significant computation to be going on here, and running strace shows this simple program making many more system calls than ps or pgrep would under most modes of operation.

One optimization that I'd expect to help based on observed syscall behavior is reading from files in /proc with a larger buffer size.

The below is what I see for reading from /proc/some-program-pid/environ:

read(4, "LS_COLORS=rs=0:di=01;34:ln=01;36", 32) = 32
read(4, ":mh=00:pi=40;33:so=01;35:do=01;3"..., 64) = 64
read(4, "31;01:su=37;41:sg=30;43:ca=30;41"..., 128) = 128
read(4, ":*.lzma=01;31:*.tlz=01;31:*.txz="..., 256) = 256
read(4, "1:*.rz=01;31:*.jpg=01;35:*.jpeg="..., 512) = 512
read(4, ".gl=01;35:*.dl=01;35:*.webm=01;3"..., 1024) = 1024
...

This ends up being around eight or nine syscalls where a single one would do if we used a reasonable buffer size like 16384. If we want to avoid oversized Vecs, we can read into a stack buffer and copy into a Vec; this would still be much faster than suffering syscall overhead.

In addition, it might be possible to refactor the API so that creating a sysinfo::System does no system calls (in much the same way Vec::new() does no allocation) and add options to refresh_all to specify which pieces of data to read. This would decrease the number of entries hit in each /proc entry and should also significantly decrease the number of system calls made.

If these ideas sound reasonable I can write a patch.

Clarification of licensing

When attempting to package sysinfo for Debian, I stumbled over some inconsistency with licensing of the project:

  • A toplevel LICENSE file contains the MIT license text
  • The Cargo.toml file says LGPL-3.0+
  • The rust source files contain a copyright notice without any reference to the license

I assume you intended to license the project under LGPL-3.0+, could you please clarify that, e.g. by replacing the LICENSE file contents by the LGPL-3.0+ text, or if it should be MIT licensed, by writing that into the Cargo.toml file? Thanks a lot.

panic when get linux disk info

The test code is very simple:

extern crate sysinfo;
use sysinfo::{System, SystemExt};

fn main() {
    let s = System::new();
    println!("total memory: {}", s.get_total_memory());
    println!("total cpu cores: {}", s.get_processor_list().len());
}

the panic backtrace:

RUST_BACKTRACE=1 ./target/debug/sysinfo
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "No such file or directory" } }', /checkout/src/libcore/result.rs:860
stack backtrace:
   1:     0x55efabcfdd99 - std::sys::imp::backtrace::tracing::imp::write::hbb14611794d3841b
                        at /checkout/src/libstd/sys/unix/backtrace/tracing/gcc_s.rs:42
   2:     0x55efabd0096e - std::panicking::default_hook::{{closure}}::h6ed906c7818ac88c
                        at /checkout/src/libstd/panicking.rs:351
   3:     0x55efabd00574 - std::panicking::default_hook::h23eeafbf7c1c05c3
                        at /checkout/src/libstd/panicking.rs:367
   4:     0x55efabd00d0b - std::panicking::rust_panic_with_hook::hd0067971b6d1240e
                        at /checkout/src/libstd/panicking.rs:545
   5:     0x55efabd00b94 - std::panicking::begin_panic::h1fd1f10a3de8f902
                        at /checkout/src/libstd/panicking.rs:507
   6:     0x55efabd00b09 - std::panicking::begin_panic_fmt::haa043917b5d6f21b
                        at /checkout/src/libstd/panicking.rs:491
   7:     0x55efabd00a97 - rust_begin_unwind
                        at /checkout/src/libstd/panicking.rs:467
   8:     0x55efabd283ed - core::panicking::panic_fmt::he9c7f335d160b59d
                        at /checkout/src/libcore/panicking.rs:69
   9:     0x55efabcd86a2 - core::result::unwrap_failed::h4d928bd97e49e0a6
                        at /checkout/src/libcore/macros.rs:29
  10:     0x55efabccd608 - <core::result::Result<T, E>>::unwrap::h5d22eb351173816f
                        at /checkout/src/libcore/result.rs:737
  11:     0x55efabcf3113 - sysinfo::linux::system::get_all_data::h57c5a3a2a1e56705
                        at /home/pingcap/.cargo/registry/src/github.com-1ecc6299db9ec823/sysinfo-0.2.7/src/linux/system.rs:238
  12:     0x55efabcef98b - sysinfo::linux::disk::new_disk::hd348afa584fe4d3b
                        at /home/pingcap/.cargo/registry/src/github.com-1ecc6299db9ec823/sysinfo-0.2.7/src/linux/disk.rs:37
  13:     0x55efabcf5940 - sysinfo::linux::system::get_all_disks::h57ad867ae2125280
                        at /home/pingcap/.cargo/registry/src/github.com-1ecc6299db9ec823/sysinfo-0.2.7/src/linux/system.rs:392
  14:     0x55efabcf16c6 - <sysinfo::linux::system::System as sysinfo::traits::SystemExt>::new::hfa809b791153da6b
                        at /home/pingcap/.cargo/registry/src/github.com-1ecc6299db9ec823/sysinfo-0.2.7/src/linux/system.rs:68
  15:     0x55efabcbb67a - sysinfo::main::h4522594c2b4e189e
                        at /data/office-cluster-deploy/sysinfo/src/main.rs:8
  16:     0x55efabd09b0a - __rust_maybe_catch_panic
                        at /checkout/src/libpanic_unwind/lib.rs:98
  17:     0x55efabd014b6 - std::rt::lang_start::hb7fc7ec87b663023
                        at /checkout/src/libstd/panicking.rs:429
                        at /checkout/src/libstd/panic.rs:361
                        at /checkout/src/libstd/rt.rs:57
  18:     0x55efabcbb8a2 - main
  19:     0x7f2b96308f44 - __libc_start_main
  20:     0x55efabcb9089 - <unknown>
  21:                0x0 - <unknown>

Add parent process info

It would be good to be able to create a process hierarchy for running processes. To be able to do that exposing the parent process id would be very nice. This is available on Linux as the fourth field in /proc//stat, I don't know where it's available in OS X (but it should be available, because htop can show it).

CPU usage is 0% accross all processors in example

Hi!

I was trying to run the sample, and it reported that all processors where at 0% usage, even when they were not. What is strange is that your process viewer shows some activity, while the sample does not. Any idea why?

Expose uid/gid information about processes

Hi, now I need information on uid and gid for a process. I have a few ideas how to implement it, what do you think best? I think I would want to add a common struct Uid and struct Gid to Process, which has the fields uid, ruid, svuid. We can get this from proc_bsdinfo on OS X and from /proc/PID/status on Linux. Do you have alternate suggestions for a design, should I leave out any of the fields or include more? Also, wouldn't it make sense to unify struct Process across Linux and OS X such that it isn't duplicated? Are you worried they will have to diverge in the future? If so, shouldn't this be handled via a macro?

process info should not use String

There's no expectation that any of the data in the String fields of the Process struct will be valid UTF8. sysinfo should use Vec for these.

Memory info sys.get_used_memory() on linux

Hi! I'm using openwrt linux on arm
/proc/meminfo looks like

MemTotal:         125128 kB
MemFree:           80288 kB
Buffers:            7652 kB
Cached:            21700 kB
SwapCached:            0 kB
Active:            21340 kB
Inactive:           9376 kB
Active(anon):       6764 kB
Inactive(anon):       16 kB
Active(file):      14576 kB
Inactive(file):     9360 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:                 0 kB
Writeback:             0 kB
AnonPages:          1388 kB
Mapped:             1036 kB
Shmem:              5416 kB
Slab:              10436 kB
SReclaimable:       6144 kB
SUnreclaim:         4292 kB
KernelStack:         384 kB
PageTables:          212 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:       62564 kB
Committed_AS:       9376 kB
VmallocTotal:     892928 kB
VmallocUsed:       41764 kB
VmallocChunk:     829276 kB

In this linux version i don't have MemAvailable but i have MemFree!

The some process data are empty on Windows

In sysinfo example the process environment, the command, the executable, the current working directory, and the root path are empty on Windows 7.
For example, Steam process:

  • sysinfo example screenshot:
    default
  • Process Hacker screenshot:
    default

Compiling for 32 bit results in errors

I'm not sure if there's anything wrong in my setup however I get the following when I build, there are more similar errors from disk.rs module.

     total_space = stat.f_bsize * stat.f_blocks;
   |                                          ^^^^^^^^^^^^^ expected u32, found u64
error[E0277]: the trait bound `u32: std::ops::Mul<u64>` is not satisfied

get_uptime method does not work

I compiled this code:

extern crate sysinfo;

use sysinfo::SystemExt;

fn main() {
    let mut system = sysinfo::System::new();
    system.refresh_all();
    println!("uptime: {} ", system.get_uptime());
}

and when I try to run it, I get the following output:

uptime: 0

Real uptime:

$ uptime -p
$ up 6 hours, 27 minutes

OS: Manjaro Linux
Kernel: 4.14.16-1-MANJARO

Linux: Panic when executable name includes a space

The contents of /proc/$PID/stat are separated by spaces, but when you just split the entire contents whenever you encounter a space then any binary with a space in its name will trigger a panic. Working on a patch.

Memory usage seems inaccurate

I'm writing a improved version of top, and when listing the memory usage of individual processes, I noticed that it doesn't line up with with what's reported by top or activity monitor. Is there any reason that this wouldn't be the case? I'm running MacOS Mojave.

memory usage

Also, it looks like the get_process_list() function only return processes started by me and not any started by other users, such as root. Is there a fix for this?

On Mac OS X, sysinfo returns status of "Some(Run)" for all processes

Am currently getting a status of "Some(Run)" for all processes listed through sysinfo's get_process_list() call, regardless of the actual status of those processes.

Some minimal example code:

extern crate sysinfo;
use sysinfo::SystemExt;

fn main() {
    let mut system = sysinfo::System::new();
    system.refresh_all();
    for (pid, process) in system.get_process_list() {
        println!("{}:{} status={:?}", pid, process.name, process.status);
    }
}

The above outputs everything with status=Some(Run), e.g.:

708:com.apple.DictionaryServiceHelper status=Some(Run)
8370:com.docker.osx.hyperkit.linux status=Some(Run)
2695:bash status=Some(Run)
29807:AssetCacheLocatorService status=Some(Run)
8368:com.docker.osx.hyperkit.linux status=Some(Run)
823:com.apple.WebKit.WebContent status=Some(Run)
51064:tcom status=Some(Run)
829:com.apple.WebKit.WebContent status=Some(Run)
1525:ssh-agent status=Some(Run)
800:com.apple.dock.extra status=Some(Run)
865:icdd status=Some(Run)
1470:bash status=Some(Run)
1152:com.apple.Safari.SearchHelper status=Some(Run)
931:ViewBridgeAuxiliary status=Some(Run)
1526:MTLCompilerService status=Some(Run)
1582:MTLCompilerService status=Some(Run)
3875:python status=Some(Run)
676:secd status=Some(Run)
1007:softwareupdate_notify_agent status=Some(Run)
47028:bash status=Some(Run)
50938:com.apple.iCloudHelper status=Some(Run)
870:SpotifyWebHelper status=Some(Run)
858:SocialPushAgent status=Some(Run)
46456:python status=Some(Run)
1135:EscrowSecurityAlert status=Some(Run)
835:Slack Helper status=Some(Run)
889:MTLCompilerService status=Some(Run)
390:cfprefsd status=Some(Run)
50835:mdworker status=Some(Run)
33657:VLC status=Some(Run)
702:cloudphotosd status=Some(Run)
1743:bash status=Some(Run)
885:CallHistorySyncHelper status=Some(Run)
730:ContactsAgent status=Some(Run)
754:AppleIDAuthAgent status=Some(Run)
8135:com.apple.audio.SandboxHelper status=Some(Run)
725:com.apple.geod status=Some(Run)
1123:com.apple.CommerceKit.TransactionService status=Some(Run)
... and a few hundred more ...

Inspecting the same processes via other means (e.g. ps, psutil in python etc.) show that most of them are sleeping, couple running, with a couple of zombies in there too.

System information:

sysinfo 0.3.2
rustc 1.16.0 (30cf806ef 2017-03-10)
cargo-0.17.0-nightly (f9e5481 2017-03-03)
Mac OS Sierra 10.12.14

CPU usage shouldn't be limited to 100%

In multi-core architecture (which is the norm now), it's common that a process runs on more than one processor, and so, it's cpu usage can go largely above 100%.

sysinfo::System::new() panics on Windows 10

Hi,

It seems that on certain builds of Windows 10 the sysinfo::System::new() panics:

image

The issue seems to be in windows/tools.rs file in get_translations() function:

       return Some(String::from_utf16(&v[..size - 1]).expect("invalid utf16"));

The above panics when size == 0 (and it happened on my machine).
If helpful, I can submit a pull request with my naive fix if the above.

Reported command inconsistency between mac os and Linux

On mac os, the reported command includes command line arguments. On Linux, this isn't the case. I assumed mac os would behave like Linux and implemented an "args" field for struct Process, which contains the arguments to the process - but on mac os, these are already available via the command field.

Do you want to keep this inconsistency, should I add an args field for both mac os and linux, should linux adapt to mac os or the other way around? Many options forward.

Process hierarchy incorrect on Linux

A simple test of the process list shows that it is incorrect.

fn check_process_hierarchy(parent: Option<pid_t>, processes: &HashMap<pid_t,Process>) {
    for (pid, process) in processes {
        assert_eq!(process.pid, *pid);
        assert_eq!(process.parent, parent);
        check_process_hierarchy(Some(*pid), &process.tasks);
    }
}
fn check() {
    let mut sysinfo = System::new();
    sysinfo.refresh_processes();
    check_process_hierarchy(None, sysinfo.get_process_list());
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.