created_at
stringclasses 8
values | test_patch
stringclasses 8
values | issue_numbers
listlengths 1
1
| instance_id
stringclasses 8
values | repo
stringclasses 1
value | patch
stringclasses 8
values | base_commit
stringclasses 8
values | problem_statement
stringclasses 8
values | version
stringclasses 6
values | pull_number
int64 245
1.16k
| hints_text
stringclasses 8
values | environment_setup_commit
stringclasses 6
values | FAIL_TO_PASS
listlengths 1
1
| PASS_TO_PASS
listlengths 8
234
| FAIL_TO_FAIL
listlengths 0
0
| PASS_TO_FAIL
listlengths 0
0
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2020-10-02T14:52:22Z
|
diff --git a/tests/process.rs b/tests/process.rs
--- a/tests/process.rs
+++ b/tests/process.rs
@@ -104,3 +104,25 @@ fn test_process_disk_usage() {
p.disk_usage().written_bytes
);
}
+
+#[test]
+fn cpu_usage_is_not_nan() {
+ let mut system = sysinfo::System::new();
+ system.refresh_processes();
+
+ let first_pids = system.get_processes()
+ .iter()
+ .take(10)
+ .map(|(&pid, _)| pid)
+ .collect::<Vec<_>>();
+ let mut checked = 0;
+
+ first_pids.into_iter().for_each(|pid| {
+ system.refresh_process(pid);
+ if let Some(p) = system.get_process(pid) {
+ assert!(!p.cpu_usage().is_nan());
+ checked += 1;
+ }
+ });
+ assert!(checked > 0);
+}
|
[
"366"
] |
GuillaumeGomez__sysinfo-367
|
GuillaumeGomez/sysinfo
|
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sysinfo"
-version = "0.15.2"
+version = "0.15.3"
authors = ["Guillaume Gomez <guillaume1.gomez@gmail.com>"]
description = "Library to get system information such as processes, processors, disks, components and networks"
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -377,7 +377,7 @@ impl SystemExt for System {
if found && !self.processors.is_empty() {
self.refresh_processors(Some(1));
let (new, old) = get_raw_times(&self.global_processor);
- let total_time = (if old > new { 1 } else { new - old }) as f32;
+ let total_time = (if old >= new { 1 } else { new - old }) as f32;
if let Some(p) = self.process_list.tasks.get_mut(&pid) {
compute_cpu_usage(p, self.processors.len() as u64, total_time);
diff --git a/src/windows/process.rs b/src/windows/process.rs
--- a/src/windows/process.rs
+++ b/src/windows/process.rs
@@ -739,9 +739,10 @@ pub(crate) fn compute_cpu_usage(p: &mut Process, nb_processors: u64, now: ULARGE
&mut fuser as *mut FILETIME as *mut c_void,
size_of::<FILETIME>(),
);
+ let old = check_sub(*now.QuadPart(), p.old_cpu);
p.cpu_usage = (check_sub(*sys.QuadPart(), p.old_sys_cpu) as f32
+ check_sub(*user.QuadPart(), p.old_user_cpu) as f32)
- / check_sub(*now.QuadPart(), p.old_cpu) as f32
+ / if old == 0 { 1 } else { old } as f32
/ nb_processors as f32
* 100.;
p.old_cpu = *now.QuadPart();
|
f57031a38b0d527958a58605682c52e262f3f017
|
Process cpu_usage() returns NaN in some cases
Hello,
I'm using `sysinfo` on version `0.15.2` on Linux mint 19.
`cargo -V` outputs `cargo 1.46.0 (149022b1d 2020-07-17)`.
`rustc -V` outputs `rustc 1.46.0 (04488afe3 2020-08-24)`.
When `system.refresh_process(pid)` is called too often, the cpu_usage() of this process becomes NaN (or sometimes inf).
I have tried to understand where is this comes from, and I think that the bug is in `system.rs`, in the function `refresh_process` (line 380):
```
let total_time = (if old > new { 1 } else { new - old }) as f32;
```
If by any chance `new == old`, then `total_time` would be zero.
`total_time` is then sent as an argument to `compute_cpu_usage`, which uses it in the denominator.
The code to reproduce:
```
fn main() {
let mut system: System = System::new();
system.refresh_processes();
let first_5_pids: Vec<Pid> = system.get_processes()
.iter()
.take(5)
.map(|(pid, _)| *pid as Pid)
.collect::<Vec<Pid>>();
first_5_pids.iter().for_each(|pid| {
system.refresh_process(*pid as Pid);
let proc = system.get_process(*pid as Pid).unwrap();
println!("pid: {}, cpu: {}", proc.pid(), proc.cpu_usage());
});
}
```
the output is as follows:
```
pid: 673, cpu: 0
pid: 1736, cpu: NaN
pid: 58, cpu: NaN
pid: 684, cpu: NaN
pid: 52, cpu: NaN
```
|
0.15
| 367
|
This is indeed where the bug is coming from. However, I'm not too aware on how to compare floats and check if they're equal. If you have any directions, it'd be awesome! (You can also send a PR if you want to go faster :wink: ).
I appreciate the quick reply :)
there are some crates that handle this, like [float_cmp](https://docs.rs/float-cmp/0.8.0/float_cmp/). Alternatively, you can use `round()` or something like that.
I don't know if I will have the time to send a PR though.
Best regards
I'd rather not add a dependency for such a specific case. I can always add a precision level to perform the comparison though.
I think the best practice is to `abs` the 2 floats, `abs` the difference and check if its smaller than `std::f64:: EPSILON` for example
|
8c2b5a0583404120f1a910d9af32f40fd1dd9d08
|
[
"cpu_usage_is_not_nan"
] |
[
"system::tests::test_refresh_system",
"system::tests::check_if_send_and_sync",
"test::check_memory_usage",
"system::tests::test_get_process",
"system::tests::test_refresh_process",
"test::check_users",
"test_disks",
"test_processor",
"test_process_refresh",
"test_get_cmd_line",
"test_process",
"test_process_disk_usage",
"test_send_sync",
"test_uptime",
"src/common.rs - common::DiskType (line 242) - compile",
"src/common.rs - common::DiskUsage (line 389) - compile",
"src/common.rs - common::LoadAvg (line 336) - compile",
"src/common.rs - common::NetworksIter (line 205) - compile",
"src/common.rs - common::RefreshKind::users_list (line 200)",
"src/common.rs - common::RefreshKind::with_networks (line 187)",
"src/common.rs - common::RefreshKind::without_cpu (line 193)",
"src/common.rs - common::RefreshKind::without_disks_list (line 191)",
"src/common.rs - common::RefreshKind::with_components_list (line 195)",
"src/common.rs - common::RefreshKind::networks (line 187)",
"src/common.rs - common::RefreshKind::with_disks_list (line 191)",
"src/common.rs - common::RefreshKind::without_components (line 194)",
"src/common.rs - common::RefreshKind::with_networks_list (line 188)",
"src/common.rs - common::RefreshKind::disks_list (line 191)",
"src/common.rs - common::RefreshKind::cpu (line 193)",
"src/common.rs - common::RefreshKind::everything (line 154)",
"src/common.rs - common::RefreshKind::components_list (line 195)",
"src/linux/network.rs - linux::network::Networks (line 18) - compile",
"src/common.rs - common::User (line 363) - compile",
"src/common.rs - common::RefreshKind::new (line 132)",
"src/common.rs - common::RefreshKind::with_cpu (line 193)",
"src/common.rs - common::RefreshKind::with_processes (line 189)",
"src/common.rs - common::RefreshKind::memory (line 192)",
"src/common.rs - common::RefreshKind::without_memory (line 192)",
"src/common.rs - common::RefreshKind::components (line 194)",
"src/common.rs - common::RefreshKind::without_processes (line 189)",
"src/common.rs - common::RefreshKind::disks (line 190)",
"src/common.rs - common::RefreshKind::with_disks (line 190)",
"src/common.rs - common::RefreshKind::without_components_list (line 195)",
"src/common.rs - common::RefreshKind::without_networks (line 187)",
"src/sysinfo.rs - set_open_files_limit (line 143) - compile",
"src/traits.rs - traits::ComponentExt::refresh (line 1188) - compile",
"src/traits.rs - traits::ComponentExt::get_label (line 1176) - compile",
"src/traits.rs - traits::ComponentExt::get_max (line 1152) - compile",
"src/traits.rs - traits::ComponentExt::get_temperature (line 1140) - compile",
"src/common.rs - common::RefreshKind::without_networks_list (line 188)",
"src/traits.rs - traits::DiskExt (line 24) - compile",
"src/traits.rs - traits::ComponentExt::get_critical (line 1164) - compile",
"src/traits.rs - traits::DiskExt::get_total_space (line 83) - compile",
"src/traits.rs - traits::DiskExt::get_file_system (line 59) - compile",
"src/traits.rs - traits::DiskExt::get_mount_point (line 71) - compile",
"src/traits.rs - traits::NetworkExt::get_packets_received (line 995) - compile",
"src/traits.rs - traits::DiskExt::get_name (line 47) - compile",
"src/traits.rs - traits::DiskExt::get_available_space (line 95) - compile",
"src/common.rs - common::RefreshKind::without_disks (line 190)",
"src/traits.rs - traits::NetworkExt::get_errors_on_received (line 1047) - compile",
"src/traits.rs - traits::DiskExt::get_type (line 35) - compile",
"src/traits.rs - traits::DiskExt::refresh (line 107) - compile",
"src/traits.rs - traits::NetworkExt::get_errors_on_transmitted (line 1073) - compile",
"src/traits.rs - traits::NetworkExt::get_received (line 943) - compile",
"src/traits.rs - traits::NetworkExt::get_total_received (line 956) - compile",
"src/traits.rs - traits::NetworkExt::get_total_errors_on_received (line 1060) - compile",
"src/traits.rs - traits::NetworkExt::get_total_transmitted (line 982) - compile",
"src/traits.rs - traits::NetworkExt::get_total_packets_received (line 1008) - compile",
"src/traits.rs - traits::NetworkExt::get_packets_transmitted (line 1021) - compile",
"src/traits.rs - traits::ProcessExt::cmd (line 152) - compile",
"src/traits.rs - traits::NetworksExt::refresh_networks_list (line 1115) - compile",
"src/traits.rs - traits::NetworkExt::get_total_packets_transmitted (line 1034) - compile",
"src/traits.rs - traits::NetworksExt::refresh (line 1126) - compile",
"src/traits.rs - traits::NetworkExt::get_total_errors_on_transmitted (line 1086) - compile",
"src/traits.rs - traits::NetworkExt::get_transmitted (line 969) - compile",
"src/common.rs - common::RefreshKind::with_memory (line 192)",
"src/traits.rs - traits::NetworksExt::iter (line 1102) - compile",
"src/traits.rs - traits::ProcessExt::name (line 140) - compile",
"src/traits.rs - traits::ProcessExt::disk_usage (line 304) - compile",
"src/traits.rs - traits::ProcessExt::environ (line 190) - compile",
"src/traits.rs - traits::ProcessExt::memory (line 230) - compile",
"src/traits.rs - traits::ProcessExt::kill (line 128) - compile",
"src/traits.rs - traits::ProcessExt::cpu_usage (line 290) - compile",
"src/traits.rs - traits::ProcessExt::pid (line 176) - compile",
"src/traits.rs - traits::ProcessExt::cwd (line 204) - compile",
"src/traits.rs - traits::ProcessExt::exe (line 164) - compile",
"src/traits.rs - traits::ProcessExt::parent (line 254) - compile",
"src/traits.rs - traits::ProcessExt::root (line 218) - compile",
"src/common.rs - common::RefreshKind::networks_list (line 188)",
"src/common.rs - common::RefreshKind (line 104)",
"src/common.rs - common::RefreshKind::processes (line 189)",
"src/common.rs - common::RefreshKind::with_users_list (line 200)",
"src/common.rs - common::RefreshKind::with_components (line 194)",
"src/traits.rs - traits::ProcessorExt::get_name (line 342) - compile",
"src/traits.rs - traits::ProcessorExt::get_frequency (line 378) - compile",
"src/traits.rs - traits::ProcessExt::status (line 266) - compile",
"src/traits.rs - traits::ProcessExt::virtual_memory (line 242) - compile",
"src/traits.rs - traits::ProcessorExt::get_cpu_usage (line 330) - compile",
"src/traits.rs - traits::ProcessorExt::get_brand (line 366) - compile",
"src/traits.rs - traits::ProcessExt::start_time (line 278) - compile",
"src/traits.rs - traits::SystemExt::get_boot_time (line 914) - compile",
"src/traits.rs - traits::SystemExt::get_load_average (line 924) - compile",
"src/traits.rs - traits::SystemExt::get_components_mut (line 832) - compile",
"src/traits.rs - traits::SystemExt::get_global_processor_info (line 716) - compile",
"src/traits.rs - traits::SystemExt::get_available_memory (line 770) - compile",
"src/traits.rs - traits::SystemExt::get_components (line 820) - compile",
"src/traits.rs - traits::SystemExt::get_disks_mut (line 868) - compile",
"src/traits.rs - traits::SystemExt::get_networks (line 880) - compile",
"src/traits.rs - traits::SystemExt::get_disks (line 844) - compile",
"src/traits.rs - traits::ProcessorExt::get_vendor_id (line 354) - compile",
"src/traits.rs - traits::SystemExt::get_networks_mut (line 893) - compile",
"src/traits.rs - traits::SystemExt::get_process (line 684) - compile",
"src/traits.rs - traits::SystemExt::get_free_swap (line 800) - compile",
"src/traits.rs - traits::SystemExt::get_process_by_name (line 696) - compile",
"src/traits.rs - traits::SystemExt::get_free_memory (line 754) - compile",
"src/traits.rs - traits::SystemExt::get_processes (line 672) - compile",
"src/traits.rs - traits::SystemExt::get_uptime (line 904) - compile",
"src/traits.rs - traits::SystemExt::get_processors (line 726) - compile",
"src/traits.rs - traits::SystemExt::get_total_memory (line 738) - compile",
"src/traits.rs - traits::SystemExt::refresh_all (line 657) - compile",
"src/traits.rs - traits::SystemExt::refresh_components (line 530) - compile",
"src/traits.rs - traits::SystemExt::new_all (line 416) - compile",
"src/traits.rs - traits::SystemExt::get_total_swap (line 790) - compile",
"src/traits.rs - traits::SystemExt::get_users (line 856) - compile",
"src/traits.rs - traits::SystemExt::get_used_memory (line 780) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks (line 575) - compile",
"src/traits.rs - traits::SystemExt::new (line 401) - compile",
"src/traits.rs - traits::SystemExt::get_used_swap (line 810) - compile",
"src/traits.rs - traits::SystemExt::refresh_cpu (line 520) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 632) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 641) - compile",
"src/traits.rs - traits::SystemExt::refresh_memory (line 510) - compile",
"src/traits.rs - traits::SystemExt::refresh_components_list (line 544) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 609) - compile",
"src/sysinfo.rs - (line 215)",
"src/traits.rs - traits::SystemExt::refresh_networks (line 618) - compile",
"src/traits.rs - traits::SystemExt::refresh_system (line 496) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks_list (line 589) - compile",
"src/traits.rs - traits::SystemExt::refresh_process (line 565) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes (line 554) - compile",
"src/traits.rs - traits::SystemExt::refresh_users_list (line 599) - compile",
"src/traits.rs - traits::UserExt (line 1203) - compile",
"src/traits.rs - traits::UserExt::get_groups (line 1226) - compile",
"src/traits.rs - traits::UserExt::get_name (line 1214) - compile",
"src/utils.rs - utils::get_current_pid (line 67) - compile",
"src/sysinfo.rs - (line 220)",
"src/common.rs - common::RefreshKind::without_users_list (line 200)",
"src/traits.rs - traits::SystemExt::new_with_specifics (line 430)",
"src/sysinfo.rs - (line 117)",
"src/traits.rs - traits::SystemExt::refresh_specifics (line 449)",
"src/sysinfo.rs - (line 14)"
] |
[] |
[] |
2020-01-26T22:19:43Z
|
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ Support the following platforms:
* Linux
* Raspberry
* Android
- * Mac OSX
+ * macOS
* Windows
It also compiles for Android but never been tested on it.
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -94,17 +94,19 @@ Here are the current results:
<details>
```text
-test bench_new ... bench: 10,437,759 ns/iter (+/- 531,424)
-test bench_refresh_all ... bench: 2,658,946 ns/iter (+/- 189,612)
-test bench_refresh_cpu ... bench: 13,429 ns/iter (+/- 537)
-test bench_refresh_disk_lists ... bench: 50,688 ns/iter (+/- 8,032)
-test bench_refresh_disks ... bench: 2,582 ns/iter (+/- 226)
-test bench_refresh_memory ... bench: 12,015 ns/iter (+/- 537)
-test bench_refresh_network ... bench: 23,661 ns/iter (+/- 617)
-test bench_refresh_process ... bench: 56,157 ns/iter (+/- 2,445)
-test bench_refresh_processes ... bench: 2,486,534 ns/iter (+/- 121,187)
-test bench_refresh_system ... bench: 53,739 ns/iter (+/- 6,793)
-test bench_refresh_temperatures ... bench: 25,770 ns/iter (+/- 1,164)
+test bench_new ... bench: 375,774 ns/iter (+/- 7,119)
+test bench_new_all ... bench: 10,308,642 ns/iter (+/- 422,803)
+test bench_refresh_all ... bench: 2,824,911 ns/iter (+/- 169,153)
+test bench_refresh_cpu ... bench: 13,630 ns/iter (+/- 702)
+test bench_refresh_disks ... bench: 2,558 ns/iter (+/- 14)
+test bench_refresh_disks_lists ... bench: 51,737 ns/iter (+/- 5,712)
+test bench_refresh_memory ... bench: 12,006 ns/iter (+/- 277)
+test bench_refresh_networks ... bench: 223,858 ns/iter (+/- 28,537)
+test bench_refresh_networks_list ... bench: 232,934 ns/iter (+/- 34,344)
+test bench_refresh_process ... bench: 78,925 ns/iter (+/- 12,421)
+test bench_refresh_processes ... bench: 2,235,119 ns/iter (+/- 137,403)
+test bench_refresh_system ... bench: 52,832 ns/iter (+/- 6,704)
+test bench_refresh_temperatures ... bench: 25,079 ns/iter (+/- 2,258)
```
</details>
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -113,36 +115,40 @@ test bench_refresh_temperatures ... bench: 25,770 ns/iter (+/- 1,164)
<details>
```text
-test bench_new ... bench: 61,548,071 ns/iter (+/- 196,093,742)
-test bench_refresh_all ... bench: 2,541,951 ns/iter (+/- 482,285)
-test bench_refresh_cpu ... bench: 460 ns/iter (+/- 478)
-test bench_refresh_disk_lists ... bench: 152,940 ns/iter (+/- 8,330)
-test bench_refresh_disks ... bench: 55,597 ns/iter (+/- 9,629)
-test bench_refresh_memory ... bench: 2,130 ns/iter (+/- 486)
-test bench_refresh_network ... bench: 212 ns/iter (+/- 216)
-test bench_refresh_process ... bench: 38 ns/iter (+/- 33)
-test bench_refresh_processes ... bench: 2,175,034 ns/iter (+/- 315,585)
-test bench_refresh_system ... bench: 2,508 ns/iter (+/- 224)
-test bench_refresh_temperatures ... bench: 1 ns/iter (+/- 0)
+test bench_new ... bench: 14,738,570 ns/iter (+/- 586,107)
+test bench_new_all ... bench: 27,132,490 ns/iter (+/- 1,292,307)
+test bench_refresh_all ... bench: 3,075,022 ns/iter (+/- 110,711)
+test bench_refresh_cpu ... bench: 392 ns/iter (+/- 30)
+test bench_refresh_disks ... bench: 41,778 ns/iter (+/- 954)
+test bench_refresh_disks_lists ... bench: 113,942 ns/iter (+/- 4,240)
+test bench_refresh_memory ... bench: 578 ns/iter (+/- 41)
+test bench_refresh_networks ... bench: 38,178 ns/iter (+/- 3,718)
+test bench_refresh_networks_list ... bench: 668,390 ns/iter (+/- 30,642)
+test bench_refresh_process ... bench: 745 ns/iter (+/- 62)
+test bench_refresh_processes ... bench: 1,179,581 ns/iter (+/- 188,119)
+test bench_refresh_system ... bench: 1,230,542 ns/iter (+/- 64,231)
+test bench_refresh_temperatures ... bench: 1,231,260 ns/iter (+/- 111,274)
```
</details>
-**OSX**
+**macOS**
<details>
```text
-test bench_new ... bench: 4,713,851 ns/iter (+/- 1,080,986)
-test bench_refresh_all ... bench: 1,639,098 ns/iter (+/- 191,147)
-test bench_refresh_cpu ... bench: 10,651 ns/iter (+/- 1,635)
-test bench_refresh_disk_lists ... bench: 29,327 ns/iter (+/- 3,104)
-test bench_refresh_disks ... bench: 942 ns/iter (+/- 79)
-test bench_refresh_memory ... bench: 3,417 ns/iter (+/- 654)
-test bench_refresh_network ... bench: 34,497 ns/iter (+/- 2,681)
-test bench_refresh_process ... bench: 4,272 ns/iter (+/- 549)
-test bench_refresh_processes ... bench: 782,977 ns/iter (+/- 30,958)
-test bench_refresh_system ... bench: 336,008 ns/iter (+/- 43,015)
-test bench_refresh_temperatures ... bench: 294,323 ns/iter (+/- 41,612)
+test bench_new ... bench: 54,862 ns/iter (+/- 6,528)
+test bench_new_all ... bench: 4,989,120 ns/iter (+/- 1,001,529)
+test bench_refresh_all ... bench: 1,924,596 ns/iter (+/- 341,209)
+test bench_refresh_cpu ... bench: 10,521 ns/iter (+/- 1,623)
+test bench_refresh_disks ... bench: 945 ns/iter (+/- 95)
+test bench_refresh_disks_lists ... bench: 29,315 ns/iter (+/- 3,076)
+test bench_refresh_memory ... bench: 3,275 ns/iter (+/- 143)
+test bench_refresh_networks ... bench: 200,670 ns/iter (+/- 28,674)
+test bench_refresh_networks_list ... bench: 200,263 ns/iter (+/- 31,473)
+test bench_refresh_process ... bench: 4,009 ns/iter (+/- 584)
+test bench_refresh_processes ... bench: 790,834 ns/iter (+/- 61,236)
+test bench_refresh_system ... bench: 335,144 ns/iter (+/- 35,713)
+test bench_refresh_temperatures ... bench: 298,823 ns/iter (+/- 77,589)
```
</details>
diff --git a/benches/basic.rs b/benches/basic.rs
--- a/benches/basic.rs
+++ b/benches/basic.rs
@@ -4,6 +4,7 @@ extern crate sysinfo;
extern crate test;
use sysinfo::SystemExt;
+use sysinfo::get_current_pid;
#[bench]
fn bench_new(b: &mut test::Bencher) {
diff --git a/benches/basic.rs b/benches/basic.rs
--- a/benches/basic.rs
+++ b/benches/basic.rs
@@ -12,9 +13,16 @@ fn bench_new(b: &mut test::Bencher) {
});
}
+#[bench]
+fn bench_new_all(b: &mut test::Bencher) {
+ b.iter(|| {
+ sysinfo::System::new_all();
+ });
+}
+
#[bench]
fn bench_refresh_all(b: &mut test::Bencher) {
- let mut s = sysinfo::System::new();
+ let mut s = sysinfo::System::new_all();
b.iter(move || {
s.refresh_all();
diff --git a/benches/basic.rs b/benches/basic.rs
--- a/benches/basic.rs
+++ b/benches/basic.rs
@@ -23,7 +31,7 @@ fn bench_refresh_all(b: &mut test::Bencher) {
#[bench]
fn bench_refresh_system(b: &mut test::Bencher) {
- let mut s = sysinfo::System::new();
+ let mut s = sysinfo::System::new_all();
s.refresh_system();
b.iter(move || {
diff --git a/benches/basic.rs b/benches/basic.rs
--- a/benches/basic.rs
+++ b/benches/basic.rs
@@ -35,6 +43,7 @@ fn bench_refresh_system(b: &mut test::Bencher) {
fn bench_refresh_processes(b: &mut test::Bencher) {
let mut s = sysinfo::System::new();
+ s.refresh_processes(); // to load the whole processes list a first time.
b.iter(move || {
s.refresh_processes();
});
diff --git a/benches/basic.rs b/benches/basic.rs
--- a/benches/basic.rs
+++ b/benches/basic.rs
@@ -45,7 +54,8 @@ fn bench_refresh_process(b: &mut test::Bencher) {
let mut s = sysinfo::System::new();
s.refresh_all();
- let pid = *s.get_process_list().iter().take(1).next().unwrap().0;
+ // to be sure it'll exist for at least as long as we run
+ let pid = get_current_pid().expect("failed to get current pid");
b.iter(move || {
s.refresh_process(pid);
});
diff --git a/benches/basic.rs b/benches/basic.rs
--- a/benches/basic.rs
+++ b/benches/basic.rs
@@ -53,7 +63,7 @@ fn bench_refresh_process(b: &mut test::Bencher) {
#[bench]
fn bench_refresh_disks(b: &mut test::Bencher) {
- let mut s = sysinfo::System::new();
+ let mut s = sysinfo::System::new_all();
b.iter(move || {
s.refresh_disks();
diff --git a/benches/basic.rs b/benches/basic.rs
--- a/benches/basic.rs
+++ b/benches/basic.rs
@@ -61,20 +71,29 @@ fn bench_refresh_disks(b: &mut test::Bencher) {
}
#[bench]
-fn bench_refresh_disk_lists(b: &mut test::Bencher) {
+fn bench_refresh_disks_lists(b: &mut test::Bencher) {
let mut s = sysinfo::System::new();
b.iter(move || {
- s.refresh_disk_list();
+ s.refresh_disks_list();
});
}
#[bench]
-fn bench_refresh_network(b: &mut test::Bencher) {
+fn bench_refresh_networks(b: &mut test::Bencher) {
+ let mut s = sysinfo::System::new_all();
+
+ b.iter(move || {
+ s.refresh_networks();
+ });
+}
+
+#[bench]
+fn bench_refresh_networks_list(b: &mut test::Bencher) {
let mut s = sysinfo::System::new();
b.iter(move || {
- s.refresh_network();
+ s.refresh_networks_list();
});
}
diff --git a/benches/basic.rs b/benches/basic.rs
--- a/benches/basic.rs
+++ b/benches/basic.rs
@@ -98,7 +117,7 @@ fn bench_refresh_cpu(b: &mut test::Bencher) {
#[bench]
fn bench_refresh_temperatures(b: &mut test::Bencher) {
- let mut s = sysinfo::System::new();
+ let mut s = sysinfo::System::new_all();
b.iter(move || {
s.refresh_temperatures();
diff --git a/src/sysinfo.rs b/src/sysinfo.rs
--- a/src/sysinfo.rs
+++ b/src/sysinfo.rs
@@ -205,9 +209,21 @@ pub enum Signal {
Sys = 31,
}
+/// A struct represents system load average value.
+#[repr(C)]
+#[derive(Default, Debug, Clone)]
+pub struct LoadAvg {
+ /// Average load within one minute.
+ pub one: f64,
+ /// Average load within five minutes.
+ pub five: f64,
+ /// Average load within fifteen minutes.
+ pub fifteen: f64,
+}
+
#[cfg(test)]
mod test {
- use traits::{ProcessExt, SystemExt};
+ use super::*;
#[test]
fn check_memory_usage() {
diff --git a/src/system.rs b/src/system.rs
--- a/src/system.rs
+++ b/src/system.rs
@@ -25,7 +25,12 @@ mod tests {
#[test]
fn test_refresh_process() {
let mut sys = System::new();
- assert!(sys.refresh_process(utils::get_current_pid().expect("failed to get current pid")));
+ assert!(sys.get_process_list().is_empty(), "no process should be listed!");
+ sys.refresh_processes();
+ assert!(
+ sys.refresh_process(utils::get_current_pid().expect("failed to get current pid")),
+ "process not listed",
+ );
}
#[test]
diff --git a/tests/process.rs b/tests/process.rs
--- a/tests/process.rs
+++ b/tests/process.rs
@@ -8,7 +8,9 @@ extern crate sysinfo;
#[test]
fn test_process() {
- use sysinfo::{ProcessExt, SystemExt};
+ #[cfg(not(windows))]
+ use sysinfo::ProcessExt;
+ use sysinfo::SystemExt;
let mut s = sysinfo::System::new();
s.refresh_processes();
|
[
"215"
] |
GuillaumeGomez__sysinfo-245
|
GuillaumeGomez/sysinfo
|
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,17 +16,15 @@ build = "build.rs"
cfg-if = "0.1"
rayon = "^1.0"
doc-comment = "0.3"
+once_cell = "1.0"
[target.'cfg(windows)'.dependencies]
-winapi = { version = "0.3", features = ["fileapi", "handleapi", "ioapiset", "minwindef", "pdh", "psapi", "synchapi", "sysinfoapi", "winbase", "winerror", "winioctl", "winnt", "oleauto", "wbemcli", "rpcdce", "combaseapi", "objidl", "objbase"] }
+winapi = { version = "0.3", features = ["fileapi", "handleapi", "ifdef", "ioapiset", "minwindef", "pdh", "psapi", "synchapi", "sysinfoapi", "winbase", "winerror", "winioctl", "winnt", "oleauto", "wbemcli", "rpcdce", "combaseapi", "objidl", "objbase", "powerbase", "netioapi"] }
ntapi = "0.3"
[target.'cfg(not(any(target_os = "unknown", target_arch = "wasm32")))'.dependencies]
libc = "0.2"
-[target.'cfg(unix)'.dependencies]
-once_cell = "1.0"
-
[lib]
name = "sysinfo"
crate_type = ["rlib", "cdylib"]
diff --git a/examples/src/simple.c b/examples/src/simple.c
--- a/examples/src/simple.c
+++ b/examples/src/simple.c
@@ -63,19 +63,19 @@ bool process_loop(pid_t pid, CProcess process, void *data) {
int main() {
CSystem system = sysinfo_init();
sysinfo_refresh_all(system);
- printf("total memory: %ld\n", sysinfo_get_total_memory(system));
- printf("free memory: %ld\n", sysinfo_get_free_memory(system));
- printf("used memory: %ld\n", sysinfo_get_used_memory(system));
- printf("total swap: %ld\n", sysinfo_get_total_swap(system));
- printf("free swap: %ld\n", sysinfo_get_free_swap(system));
- printf("used swap: %ld\n", sysinfo_get_used_swap(system));
- printf("network income: %ld\n", sysinfo_get_network_income(system));
- printf("network outcome: %ld\n", sysinfo_get_network_outcome(system));
+ printf("total memory: %ld\n", sysinfo_get_total_memory(system));
+ printf("free memory: %ld\n", sysinfo_get_free_memory(system));
+ printf("used memory: %ld\n", sysinfo_get_used_memory(system));
+ printf("total swap: %ld\n", sysinfo_get_total_swap(system));
+ printf("free swap: %ld\n", sysinfo_get_free_swap(system));
+ printf("used swap: %ld\n", sysinfo_get_used_swap(system));
+ printf("networks income: %ld\n", sysinfo_get_networks_income(system));
+ printf("networks outcome: %ld\n", sysinfo_get_networks_outcome(system));
unsigned int len = 0, i = 0;
float *procs = NULL;
sysinfo_get_processors_usage(system, &len, &procs);
while (i < len) {
- printf("Processor #%d usage: %f\n", i, procs[i]);
+ printf("Processor #%d usage: %f%%\n", i, procs[i]);
i += 1;
}
free(procs);
diff --git a/examples/src/simple.rs b/examples/src/simple.rs
--- a/examples/src/simple.rs
+++ b/examples/src/simple.rs
@@ -1,43 +1,126 @@
-//
+//
// Sysinfo
-//
+//
// Copyright (c) 2017 Guillaume Gomez
//
#![crate_type = "bin"]
-
#![allow(unused_must_use, non_upper_case_globals)]
extern crate sysinfo;
-use sysinfo::{NetworkExt, Pid, ProcessExt, ProcessorExt, Signal, System, SystemExt};
-use sysinfo::Signal::*;
use std::io::{self, BufRead, Write};
use std::str::FromStr;
+use sysinfo::Signal::*;
+use sysinfo::{NetworkExt, NetworksExt, Pid, ProcessExt, ProcessorExt, Signal, System, SystemExt};
-const signals: [Signal; 31] = [Hangup, Interrupt, Quit, Illegal, Trap, Abort, Bus,
- FloatingPointException, Kill, User1, Segv, User2, Pipe, Alarm,
- Term, Stklft, Child, Continue, Stop, TSTP, TTIN, TTOU, Urgent,
- XCPU, XFSZ, VirtualAlarm, Profiling, Winch, IO, Power, Sys];
+const signals: [Signal; 31] = [
+ Hangup,
+ Interrupt,
+ Quit,
+ Illegal,
+ Trap,
+ Abort,
+ Bus,
+ FloatingPointException,
+ Kill,
+ User1,
+ Segv,
+ User2,
+ Pipe,
+ Alarm,
+ Term,
+ Stklft,
+ Child,
+ Continue,
+ Stop,
+ TSTP,
+ TTIN,
+ TTOU,
+ Urgent,
+ XCPU,
+ XFSZ,
+ VirtualAlarm,
+ Profiling,
+ Winch,
+ IO,
+ Power,
+ Sys,
+];
fn print_help() {
writeln!(&mut io::stdout(), "== Help menu ==");
writeln!(&mut io::stdout(), "help : show this menu");
- writeln!(&mut io::stdout(), "signals : show the available signals");
- writeln!(&mut io::stdout(), "refresh : reloads all processes' information");
- writeln!(&mut io::stdout(), "refresh [pid] : reloads corresponding process' information");
- writeln!(&mut io::stdout(), "refresh_disks : reloads only disks' information");
- writeln!(&mut io::stdout(), "show [pid | name] : show information of the given process \
- corresponding to [pid | name]");
- writeln!(&mut io::stdout(), "kill [pid] [signal]: send [signal] to the process with this \
- [pid]. 0 < [signal] < 32");
- writeln!(&mut io::stdout(), "proc : Displays proc state");
- writeln!(&mut io::stdout(), "memory : Displays memory state");
- writeln!(&mut io::stdout(), "temperature : Displays components' temperature");
- writeln!(&mut io::stdout(), "disks : Displays disks' information");
- writeln!(&mut io::stdout(), "network : Displays network' information");
- writeln!(&mut io::stdout(), "all : Displays all process name and pid");
- writeln!(&mut io::stdout(), "uptime : Displays system uptime");
+ writeln!(
+ &mut io::stdout(),
+ "signals : show the available signals"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "refresh : reloads all processes' information"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "refresh [pid] : reloads corresponding process' information"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "refresh_disks : reloads only disks' information"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "show [pid | name] : show information of the given process \
+ corresponding to [pid | name]"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "kill [pid] [signal]: send [signal] to the process with this \
+ [pid]. 0 < [signal] < 32"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "procd : Displays processors state"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "memory : Displays memory state"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "temperature : Displays components' temperature"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "disks : Displays disks' information"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "network : Displays network' information"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "all : Displays all process name and pid"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "uptime : Displays system uptime"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "vendor_id : Displays processor vendor id"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "brand : Displays processor brand"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "load_avg : Displays system load average"
+ );
+ writeln!(
+ &mut io::stdout(),
+ "frequency : Displays processor frequency"
+ );
writeln!(&mut io::stdout(), "quit : exit the program");
}
diff --git a/examples/src/simple.rs b/examples/src/simple.rs
--- a/examples/src/simple.rs
+++ b/examples/src/simple.rs
@@ -46,7 +129,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
"help" => print_help(),
"refresh_disks" => {
writeln!(&mut io::stdout(), "Refreshing disk list...");
- sys.refresh_disk_list();
+ sys.refresh_disks_list();
writeln!(&mut io::stdout(), "Done.");
}
"signals" => {
diff --git a/examples/src/simple.rs b/examples/src/simple.rs
--- a/examples/src/simple.rs
+++ b/examples/src/simple.rs
@@ -57,32 +140,91 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
nb += 1;
}
}
- "proc" => {
- // Note: you should refresh a few times before using this, so that usage statistics can be ascertained
+ "procs" => {
+ // Note: you should refresh a few times before using this, so that usage statistics
+ // can be ascertained
let procs = sys.get_processor_list();
- writeln!(&mut io::stdout(), "total process usage: {}%", procs[0].get_cpu_usage());
+ writeln!(
+ &mut io::stdout(),
+ "total process usage: {}%",
+ procs[0].get_cpu_usage()
+ );
for proc_ in procs.iter().skip(1) {
writeln!(&mut io::stdout(), "{:?}", proc_);
}
}
"memory" => {
- writeln!(&mut io::stdout(), "total memory: {} KiB", sys.get_total_memory());
- writeln!(&mut io::stdout(), "used memory : {} KiB", sys.get_used_memory());
- writeln!(&mut io::stdout(), "total swap : {} KiB", sys.get_total_swap());
- writeln!(&mut io::stdout(), "used swap : {} KiB", sys.get_used_swap());
+ writeln!(
+ &mut io::stdout(),
+ "total memory: {} KiB",
+ sys.get_total_memory()
+ );
+ writeln!(
+ &mut io::stdout(),
+ "used memory : {} KiB",
+ sys.get_used_memory()
+ );
+ writeln!(
+ &mut io::stdout(),
+ "total swap : {} KiB",
+ sys.get_total_swap()
+ );
+ writeln!(
+ &mut io::stdout(),
+ "used swap : {} KiB",
+ sys.get_used_swap()
+ );
}
"quit" | "exit" => return true,
"all" => {
for (pid, proc_) in sys.get_process_list() {
- writeln!(&mut io::stdout(), "{}:{} status={:?}", pid, proc_.name(), proc_.status());
+ writeln!(
+ &mut io::stdout(),
+ "{}:{} status={:?}",
+ pid,
+ proc_.name(),
+ proc_.status()
+ );
}
}
+ "frequency" => {
+ let procs = sys.get_processor_list();
+ // On windows, the first processor is the "all processors", so not interesting in here.
+ writeln!(
+ &mut io::stdout(),
+ "{} MHz",
+ procs[if procs.len() > 1 { 1 } else { 0 }].get_frequency()
+ );
+ }
+ "vendor_id" => {
+ writeln!(
+ &mut io::stdout(),
+ "vendor ID: {}",
+ sys.get_processor_list()[0].get_vendor_id()
+ );
+ }
+ "brand" => {
+ writeln!(
+ &mut io::stdout(),
+ "brand: {}",
+ sys.get_processor_list()[0].get_brand()
+ );
+ }
+ "load_avg" => {
+ let load_avg = sys.get_load_average();
+ writeln!(&mut io::stdout(), "one minute : {}%", load_avg.one);
+ writeln!(&mut io::stdout(), "five minutes : {}%", load_avg.five);
+ writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
+ }
e if e.starts_with("show ") => {
- let tmp : Vec<&str> = e.split(' ').collect();
+ let tmp: Vec<&str> = e.split(' ').collect();
if tmp.len() != 2 {
- writeln!(&mut io::stdout(), "show command takes a pid or a name in parameter!");
+ writeln!(
+ &mut io::stdout(),
+ "show command takes a pid or a name in parameter!"
+ );
writeln!(&mut io::stdout(), "example: show 1254");
} else if let Ok(pid) = Pid::from_str(tmp[1]) {
match sys.get_process(pid) {
diff --git a/examples/src/simple.rs b/examples/src/simple.rs
--- a/examples/src/simple.rs
+++ b/examples/src/simple.rs
@@ -103,33 +245,52 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
}
}
"network" => {
- writeln!(&mut io::stdout(), "input data : {} B", sys.get_network().get_income());
- writeln!(&mut io::stdout(), "output data: {} B", sys.get_network().get_outcome());
+ for (interface_name, data) in sys.get_networks().iter() {
+ writeln!(
+ &mut io::stdout(),
+ "{}:\n input data (new / total): {} / {} B\n output data (new / total): {} / {} B",
+ interface_name,
+ data.get_income(),
+ data.get_total_income(),
+ data.get_outcome(),
+ data.get_total_outcome(),
+ );
+ }
}
"show" => {
- writeln!(&mut io::stdout(), "'show' command expects a pid number or a process name");
+ writeln!(
+ &mut io::stdout(),
+ "'show' command expects a pid number or a process name"
+ );
}
e if e.starts_with("kill ") => {
- let tmp : Vec<&str> = e.split(' ').collect();
+ let tmp: Vec<&str> = e.split(' ').collect();
if tmp.len() != 3 {
- writeln!(&mut io::stdout(),
- "kill command takes the pid and a signal number in parameter !");
+ writeln!(
+ &mut io::stdout(),
+ "kill command takes the pid and a signal number in parameter !"
+ );
writeln!(&mut io::stdout(), "example: kill 1254 9");
} else {
let pid = Pid::from_str(tmp[1]).unwrap();
let signal = i32::from_str(tmp[2]).unwrap();
if signal < 1 || signal > 31 {
- writeln!(&mut io::stdout(),
- "Signal must be between 0 and 32 ! See the signals list with the \
- signals command");
+ writeln!(
+ &mut io::stdout(),
+ "Signal must be between 0 and 32 ! See the signals list with the \
+ signals command"
+ );
} else {
match sys.get_process(pid) {
Some(p) => {
- writeln!(&mut io::stdout(), "kill: {}",
- p.kill(*signals.get(signal as usize - 1).unwrap()));
- },
+ writeln!(
+ &mut io::stdout(),
+ "kill: {}",
+ p.kill(*signals.get(signal as usize - 1).unwrap())
+ );
+ }
None => {
writeln!(&mut io::stdout(), "pid not found");
}
diff --git a/examples/src/simple.rs b/examples/src/simple.rs
--- a/examples/src/simple.rs
+++ b/examples/src/simple.rs
@@ -149,11 +310,13 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
let hours = uptime / 3600;
uptime -= hours * 3600;
let minutes = uptime / 60;
- writeln!(&mut io::stdout(),
- "{} days {} hours {} minutes",
- days,
- hours,
- minutes);
+ writeln!(
+ &mut io::stdout(),
+ "{} days {} hours {} minutes",
+ days,
+ hours,
+ minutes
+ );
}
x if x.starts_with("refresh") => {
if x == "refresh" {
diff --git a/examples/src/simple.rs b/examples/src/simple.rs
--- a/examples/src/simple.rs
+++ b/examples/src/simple.rs
@@ -162,25 +325,40 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
writeln!(&mut io::stdout(), "Done.");
} else if x.starts_with("refresh ") {
writeln!(&mut io::stdout(), "Getting process' information...");
- if let Some(pid) = x.split(' ').filter_map(|pid| pid.parse().ok()).take(1).next() {
+ if let Some(pid) = x
+ .split(' ')
+ .filter_map(|pid| pid.parse().ok())
+ .take(1)
+ .next()
+ {
if sys.refresh_process(pid) {
writeln!(&mut io::stdout(), "Process `{}` updated successfully", pid);
} else {
- writeln!(&mut io::stdout(), "Process `{}` couldn't be updated...", pid);
+ writeln!(
+ &mut io::stdout(),
+ "Process `{}` couldn't be updated...",
+ pid
+ );
}
} else {
writeln!(&mut io::stdout(), "Invalid [pid] received...");
}
} else {
- writeln!(&mut io::stdout(),
- "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
- list.", x);
+ writeln!(
+ &mut io::stdout(),
+ "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
+ list.",
+ x
+ );
}
}
e => {
- writeln!(&mut io::stdout(),
- "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
- list.", e);
+ writeln!(
+ &mut io::stdout(),
+ "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
+ list.",
+ e
+ );
}
}
false
diff --git a/examples/src/simple.rs b/examples/src/simple.rs
--- a/examples/src/simple.rs
+++ b/examples/src/simple.rs
@@ -188,7 +366,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
fn main() {
println!("Getting processes' information...");
- let mut t = System::new();
+ let mut t = System::new_all();
println!("Done.");
let t_stin = io::stdin();
let mut stin = t_stin.lock();
diff --git a/examples/src/simple.rs b/examples/src/simple.rs
--- a/examples/src/simple.rs
+++ b/examples/src/simple.rs
@@ -201,6 +379,12 @@ fn main() {
io::stdout().flush();
stin.read_line(&mut input);
+ if input.is_empty() {
+ // The string is empty, meaning there is no '\n', meaning
+ // that the user used CTRL+D so we can just quit!
+ println!("\nLeaving, bye!");
+ break;
+ }
if (&input as &str).ends_with('\n') {
input.pop();
}
diff --git a/src/c_interface.rs b/src/c_interface.rs
--- a/src/c_interface.rs
+++ b/src/c_interface.rs
@@ -7,7 +7,7 @@
use libc::{self, c_char, c_float, c_uint, c_void, pid_t, size_t};
use std::borrow::BorrowMut;
use std::ffi::CString;
-use {NetworkExt, Process, ProcessExt, ProcessorExt, System, SystemExt};
+use {NetworkExt, NetworksExt, Process, ProcessExt, ProcessorExt, System, SystemExt};
/// Equivalent of `System` struct.
pub type CSystem = *mut c_void;
diff --git a/src/c_interface.rs b/src/c_interface.rs
--- a/src/c_interface.rs
+++ b/src/c_interface.rs
@@ -131,14 +131,14 @@ pub extern "C" fn sysinfo_refresh_disks(system: CSystem) {
Box::into_raw(system);
}
-/// Equivalent of `System::refresh_disk_list()`.
+/// Equivalent of `System::refresh_disks_list()`.
#[no_mangle]
-pub extern "C" fn sysinfo_refresh_disk_list(system: CSystem) {
+pub extern "C" fn sysinfo_refresh_disks_list(system: CSystem) {
assert!(!system.is_null());
let mut system: Box<System> = unsafe { Box::from_raw(system as *mut System) };
{
let system: &mut System = system.borrow_mut();
- system.refresh_disk_list();
+ system.refresh_disks_list();
}
Box::into_raw(system);
}
diff --git a/src/c_interface.rs b/src/c_interface.rs
--- a/src/c_interface.rs
+++ b/src/c_interface.rs
@@ -203,22 +203,30 @@ pub extern "C" fn sysinfo_get_used_swap(system: CSystem) -> size_t {
ret
}
-/// Equivalent of `system::get_network().get_income()`.
+/// Equivalent of
+/// `system::get_networks().iter().fold(0, |acc, (_, data)| acc + data.get_income() as size_t)`.
#[no_mangle]
-pub extern "C" fn sysinfo_get_network_income(system: CSystem) -> size_t {
+pub extern "C" fn sysinfo_get_networks_income(system: CSystem) -> size_t {
assert!(!system.is_null());
let system: Box<System> = unsafe { Box::from_raw(system as *mut System) };
- let ret = system.get_network().get_income() as size_t;
+ let ret = system
+ .get_networks()
+ .iter()
+ .fold(0, |acc, (_, data)| acc + data.get_income() as size_t);
Box::into_raw(system);
ret
}
-/// Equivalent of `system::get_network().get_outcome()`.
+/// Equivalent of
+/// `system::get_networks().iter().fold(0, |acc, (_, data)| acc + data.get_outcome() as size_t)`.
#[no_mangle]
-pub extern "C" fn sysinfo_get_network_outcome(system: CSystem) -> size_t {
+pub extern "C" fn sysinfo_get_networks_outcome(system: CSystem) -> size_t {
assert!(!system.is_null());
let system: Box<System> = unsafe { Box::from_raw(system as *mut System) };
- let ret = system.get_network().get_outcome() as size_t;
+ let ret = system
+ .get_networks()
+ .iter()
+ .fold(0, |acc, (_, data)| acc + data.get_outcome() as size_t);
Box::into_raw(system);
ret
}
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -4,6 +4,10 @@
// Copyright (c) 2015 Guillaume Gomez
//
+use NetworkData;
+use Networks;
+use NetworksExt;
+
/// Trait to have a common fallback for the `Pid` type.
pub trait AsU32 {
/// Allows to convert `Pid` into `u32`.
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -105,16 +109,17 @@ assert_eq!(r.", stringify!($name), "(), false);
/// use sysinfo::{RefreshKind, System, SystemExt};
///
/// // We want everything except disks.
-/// let mut system = System::new_with_specifics(RefreshKind::everything().without_disk_list());
+/// let mut system = System::new_with_specifics(RefreshKind::everything().without_disks_list());
///
/// assert_eq!(system.get_disks().len(), 0);
/// assert!(system.get_process_list().len() > 0);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RefreshKind {
- network: bool,
+ networks: bool,
+ networks_list: bool,
processes: bool,
- disk_list: bool,
+ disks_list: bool,
disks: bool,
memory: bool,
cpu: bool,
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -131,9 +136,10 @@ impl RefreshKind {
///
/// let r = RefreshKind::new();
///
- /// assert_eq!(r.network(), false);
+ /// assert_eq!(r.networks(), false);
+ /// assert_eq!(r.networks_list(), false);
/// assert_eq!(r.processes(), false);
- /// assert_eq!(r.disk_list(), false);
+ /// assert_eq!(r.disks_list(), false);
/// assert_eq!(r.disks(), false);
/// assert_eq!(r.memory(), false);
/// assert_eq!(r.cpu(), false);
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -141,10 +147,11 @@ impl RefreshKind {
/// ```
pub fn new() -> RefreshKind {
RefreshKind {
- network: false,
+ networks: false,
+ networks_list: false,
processes: false,
disks: false,
- disk_list: false,
+ disks_list: false,
memory: false,
cpu: false,
temperatures: false,
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -160,9 +167,10 @@ impl RefreshKind {
///
/// let r = RefreshKind::everything();
///
- /// assert_eq!(r.network(), true);
+ /// assert_eq!(r.networks(), true);
+ /// assert_eq!(r.networks_list(), true);
/// assert_eq!(r.processes(), true);
- /// assert_eq!(r.disk_list(), true);
+ /// assert_eq!(r.disks_list(), true);
/// assert_eq!(r.disks(), true);
/// assert_eq!(r.memory(), true);
/// assert_eq!(r.cpu(), true);
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -170,21 +178,51 @@ impl RefreshKind {
/// ```
pub fn everything() -> RefreshKind {
RefreshKind {
- network: true,
+ networks: true,
+ networks_list: true,
processes: true,
disks: true,
- disk_list: true,
+ disks_list: true,
memory: true,
cpu: true,
temperatures: true,
}
}
- impl_get_set!(network, with_network, without_network);
+ impl_get_set!(networks, with_networks, without_networks);
+ impl_get_set!(networks_list, with_networks_list, without_networks_list);
impl_get_set!(processes, with_processes, without_processes);
impl_get_set!(disks, with_disks, without_disks);
- impl_get_set!(disk_list, with_disk_list, without_disk_list);
+ impl_get_set!(disks_list, with_disks_list, without_disks_list);
impl_get_set!(memory, with_memory, without_memory);
impl_get_set!(cpu, with_cpu, without_cpu);
impl_get_set!(temperatures, with_temperatures, without_temperatures);
}
+
+/// Iterator over network interfaces.
+pub struct NetworksIter<'a> {
+ inner: std::collections::hash_map::Iter<'a, String, NetworkData>,
+}
+
+impl<'a> NetworksIter<'a> {
+ pub(crate) fn new(v: std::collections::hash_map::Iter<'a, String, NetworkData>) -> Self {
+ NetworksIter { inner: v }
+ }
+}
+
+impl<'a> Iterator for NetworksIter<'a> {
+ type Item = (&'a String, &'a NetworkData);
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.inner.next()
+ }
+}
+
+impl<'a> IntoIterator for &'a Networks {
+ type Item = (&'a String, &'a NetworkData);
+ type IntoIter = NetworksIter<'a>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+}
diff --git a/src/linux/mod.rs b/src/linux/mod.rs
--- a/src/linux/mod.rs
+++ b/src/linux/mod.rs
@@ -13,7 +13,7 @@ pub mod system;
pub use self::component::Component;
pub use self::disk::{Disk, DiskType};
-pub use self::network::NetworkData;
+pub use self::network::{NetworkData, Networks};
pub use self::process::{Process, ProcessStatus};
pub use self::processor::Processor;
pub use self::system::System;
diff --git a/src/linux/network.rs b/src/linux/network.rs
--- a/src/linux/network.rs
+++ b/src/linux/network.rs
@@ -5,79 +5,220 @@
//
use std::fs::File;
-use std::io::{Error, ErrorKind, Read};
+use std::io::Read;
+use std::path::Path;
+use std::collections::HashMap;
use NetworkExt;
+use NetworksExt;
+use NetworksIter;
-/// Contains network information.
+/// Network interfaces.
+///
+/// ```no_run
+/// use sysinfo::{NetworksExt, System, SystemExt};
+///
+/// let s = System::new_all();
+/// let networks = s.get_networks();
+/// ```
#[derive(Debug)]
-pub struct NetworkData {
- old_in: u64,
- old_out: u64,
- current_in: u64,
- current_out: u64,
+pub struct Networks {
+ interfaces: HashMap<String, NetworkData>,
}
-impl NetworkExt for NetworkData {
- fn get_income(&self) -> u64 {
- self.current_in - self.old_in
- }
+macro_rules! old_and_new {
+ ($ty_:expr, $name:ident, $old:ident) => {{
+ $ty_.$old = $ty_.$name;
+ $ty_.$name = $name;
+ }};
+ ($ty_:expr, $name:ident, $old:ident, $path:expr) => {{
+ let _tmp = $path;
+ $ty_.$old = $ty_.$name;
+ $ty_.$name = _tmp;
+ }};
+}
- fn get_outcome(&self) -> u64 {
- self.current_out - self.old_out
+fn read<P: AsRef<Path>>(parent: P, path: &str, data: &mut Vec<u8>) -> usize {
+ if let Ok(mut f) = File::open(parent.as_ref().join(path)) {
+ if let Ok(size) = f.read(data) {
+ let mut i = 0;
+ let mut ret = 0;
+
+ while i < size && i < data.len() && data[i] >= b'0' && data[i] <= b'9' {
+ ret *= 10;
+ ret += (data[i] - b'0') as usize;
+ i += 1;
+ }
+ return ret;
+ }
}
+ 0
}
-pub fn new() -> NetworkData {
- NetworkData {
- old_in: 0,
- old_out: 0,
- current_in: 0,
- current_out: 0,
+impl Networks {
+ pub(crate) fn new() -> Self {
+ Networks {
+ interfaces: HashMap::new(),
+ }
}
}
-fn read_things() -> Result<(u64, u64), Error> {
- fn read_interface_stat(iface: &str, typ: &str) -> Result<u64, Error> {
- let mut file = File::open(format!("/sys/class/net/{}/statistics/{}_bytes", iface, typ))?;
- let mut content = String::with_capacity(20);
- file.read_to_string(&mut content)?;
- content
- .trim()
- .parse()
- .map_err(|_| Error::new(ErrorKind::Other, "Failed to parse network stat"))
+impl NetworksExt for Networks {
+ fn iter<'a>(&'a self) -> NetworksIter<'a> {
+ NetworksIter::new(self.interfaces.iter())
}
- let default_interface = {
- let mut file = File::open("/proc/net/route")?;
- let mut content = String::with_capacity(800);
- file.read_to_string(&mut content)?;
- content
- .lines()
- .filter(|l| {
- l.split_whitespace()
- .nth(2)
- .map(|l| l != "00000000")
- .unwrap_or(false)
- })
- .last()
- .and_then(|l| l.split_whitespace().nth(0))
- .ok_or_else(|| Error::new(ErrorKind::Other, "Default device not found"))?
- .to_owned()
- };
-
- Ok((
- read_interface_stat(&default_interface, "rx")?,
- read_interface_stat(&default_interface, "tx")?,
- ))
+ fn refresh(&mut self) {
+ let mut v = vec![0; 30];
+
+ for (interface_name, data) in self.interfaces.iter_mut() {
+ data.update(interface_name, &mut v);
+ }
+ }
+
+ fn refresh_networks_list(&mut self) {
+ if let Ok(dir) = std::fs::read_dir("/sys/class/net/") {
+ let mut data = vec![0; 30];
+ for entry in dir {
+ if let Ok(entry) = entry {
+ let parent = &entry.path().join("statistics");
+ let entry = match entry.file_name().into_string() {
+ Ok(entry) => entry,
+ Err(_) => continue,
+ };
+ let rx_bytes = read(parent, "rx_bytes", &mut data);
+ let tx_bytes = read(parent, "tx_bytes", &mut data);
+ let rx_packets = read(parent, "rx_packets", &mut data);
+ let tx_packets = read(parent, "tx_packets", &mut data);
+ let rx_errors = read(parent, "rx_errors", &mut data);
+ let tx_errors = read(parent, "tx_errors", &mut data);
+ // let rx_compressed = read(parent, "rx_compressed", &mut data);
+ // let tx_compressed = read(parent, "tx_compressed", &mut data);
+ let interface = self.interfaces.entry(entry).or_insert_with(|| NetworkData {
+ rx_bytes,
+ old_rx_bytes: rx_bytes,
+ tx_bytes,
+ old_tx_bytes: tx_bytes,
+ rx_packets,
+ old_rx_packets: rx_packets,
+ tx_packets,
+ old_tx_packets: tx_packets,
+ rx_errors,
+ old_rx_errors: rx_errors,
+ tx_errors,
+ old_tx_errors: tx_errors,
+ // rx_compressed,
+ // old_rx_compressed: rx_compressed,
+ // tx_compressed,
+ // old_tx_compressed: tx_compressed,
+ });
+ old_and_new!(interface, rx_bytes, old_rx_bytes);
+ old_and_new!(interface, tx_bytes, old_tx_bytes);
+ old_and_new!(interface, rx_packets, old_rx_packets);
+ old_and_new!(interface, tx_packets, old_tx_packets);
+ old_and_new!(interface, rx_errors, old_rx_errors);
+ old_and_new!(interface, tx_errors, old_tx_errors);
+ // old_and_new!(interface, rx_compressed, old_rx_compressed);
+ // old_and_new!(interface, tx_compressed, old_tx_compressed);
+ }
+ }
+ }
+ }
}
-pub fn update_network(n: &mut NetworkData) {
- if let Ok((new_in, new_out)) = read_things() {
- n.old_in = n.current_in;
- n.old_out = n.current_out;
- n.current_in = new_in;
- n.current_out = new_out;
+/// Contains network information.
+#[derive(Debug)]
+pub struct NetworkData {
+ /// Total number of bytes received over interface.
+ rx_bytes: usize,
+ old_rx_bytes: usize,
+ /// Total number of bytes transmitted over interface.
+ tx_bytes: usize,
+ old_tx_bytes: usize,
+ /// Total number of packets received.
+ rx_packets: usize,
+ old_rx_packets: usize,
+ /// Total number of packets transmitted.
+ tx_packets: usize,
+ old_tx_packets: usize,
+ /// Shows the total number of packets received with error. This includes
+ /// too-long-frames errors, ring-buffer overflow errors, CRC errors,
+ /// frame alignment errors, fifo overruns, and missed packets.
+ rx_errors: usize,
+ old_rx_errors: usize,
+ /// similar to `rx_errors`
+ tx_errors: usize,
+ old_tx_errors: usize,
+ // /// Indicates the number of compressed packets received by this
+ // /// network device. This value might only be relevant for interfaces
+ // /// that support packet compression (e.g: PPP).
+ // rx_compressed: usize,
+ // old_rx_compressed: usize,
+ // /// Indicates the number of transmitted compressed packets. Note
+ // /// this might only be relevant for devices that support
+ // /// compression (e.g: PPP).
+ // tx_compressed: usize,
+ // old_tx_compressed: usize,
+}
+
+impl NetworkData {
+ fn update(&mut self, path: &str, data: &mut Vec<u8>) {
+ let path = &Path::new("/sys/class/net/").join(path).join("statistics");
+ old_and_new!(self, rx_bytes, old_rx_bytes, read(path, "rx_bytes", data));
+ old_and_new!(self, tx_bytes, old_tx_bytes, read(path, "tx_bytes", data));
+ old_and_new!(
+ self,
+ rx_packets,
+ old_rx_packets,
+ read(path, "rx_packets", data)
+ );
+ old_and_new!(
+ self,
+ tx_packets,
+ old_tx_packets,
+ read(path, "tx_packets", data)
+ );
+ old_and_new!(
+ self,
+ rx_errors,
+ old_rx_errors,
+ read(path, "rx_errors", data)
+ );
+ old_and_new!(
+ self,
+ tx_errors,
+ old_tx_errors,
+ read(path, "tx_errors", data)
+ );
+ // old_and_new!(
+ // self,
+ // rx_compressed,
+ // old_rx_compressed,
+ // read(path, "rx_compressed", data)
+ // );
+ // old_and_new!(
+ // self,
+ // tx_compressed,
+ // old_tx_compressed,
+ // read(path, "tx_compressed", data)
+ // );
+ }
+}
+
+impl NetworkExt for NetworkData {
+ fn get_income(&self) -> u64 {
+ self.rx_bytes as u64 - self.old_rx_bytes as u64
+ }
+
+ fn get_outcome(&self) -> u64 {
+ self.tx_bytes as u64 - self.old_tx_bytes as u64
+ }
+
+ fn get_total_income(&self) -> u64 {
+ self.rx_bytes as u64
+ }
+
+ fn get_total_outcome(&self) -> u64 {
+ self.rx_bytes as u64
}
- // TODO: maybe handle error here?
}
diff --git a/src/linux/processor.rs b/src/linux/processor.rs
--- a/src/linux/processor.rs
+++ b/src/linux/processor.rs
@@ -6,6 +6,9 @@
#![allow(clippy::too_many_arguments)]
+use std::fs::File;
+use std::io::Read;
+
use ProcessorExt;
/// Struct containing values to compute a CPU usage.
diff --git a/src/linux/processor.rs b/src/linux/processor.rs
--- a/src/linux/processor.rs
+++ b/src/linux/processor.rs
@@ -125,22 +128,13 @@ pub struct Processor {
cpu_usage: f32,
total_time: u64,
old_total_time: u64,
+ frequency: u64,
+ vendor_id: String,
+ brand: String,
}
impl Processor {
- #[allow(dead_code)]
- fn new() -> Processor {
- Processor {
- name: String::new(),
- old_values: CpuValues::new(),
- new_values: CpuValues::new(),
- cpu_usage: 0f32,
- total_time: 0,
- old_total_time: 0,
- }
- }
-
- fn new_with_values(
+ pub(crate) fn new_with_values(
name: &str,
user: u64,
nice: u64,
diff --git a/src/linux/processor.rs b/src/linux/processor.rs
--- a/src/linux/processor.rs
+++ b/src/linux/processor.rs
@@ -152,6 +146,9 @@ impl Processor {
steal: u64,
guest: u64,
guest_nice: u64,
+ frequency: u64,
+ vendor_id: String,
+ brand: String,
) -> Processor {
Processor {
name: name.to_owned(),
diff --git a/src/linux/processor.rs b/src/linux/processor.rs
--- a/src/linux/processor.rs
+++ b/src/linux/processor.rs
@@ -162,10 +159,13 @@ impl Processor {
cpu_usage: 0f32,
total_time: 0,
old_total_time: 0,
+ frequency,
+ vendor_id,
+ brand,
}
}
- fn set(
+ pub(crate) fn set(
&mut self,
user: u64,
nice: u64,
diff --git a/src/linux/processor.rs b/src/linux/processor.rs
--- a/src/linux/processor.rs
+++ b/src/linux/processor.rs
@@ -208,44 +208,74 @@ impl ProcessorExt for Processor {
fn get_name(&self) -> &str {
&self.name
}
-}
-pub fn new_processor(
- name: &str,
- user: u64,
- nice: u64,
- system: u64,
- idle: u64,
- iowait: u64,
- irq: u64,
- softirq: u64,
- steal: u64,
- guest: u64,
- guest_nice: u64,
-) -> Processor {
- Processor::new_with_values(
- name, user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice,
- )
-}
+ /// Returns the CPU frequency in MHz.
+ fn get_frequency(&self) -> u64 {
+ self.frequency
+ }
-pub fn set_processor(
- p: &mut Processor,
- user: u64,
- nice: u64,
- system: u64,
- idle: u64,
- iowait: u64,
- irq: u64,
- softirq: u64,
- steal: u64,
- guest: u64,
- guest_nice: u64,
-) {
- p.set(
- user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice,
- )
+ fn get_vendor_id(&self) -> &str {
+ &self.vendor_id
+ }
+
+ fn get_brand(&self) -> &str {
+ &self.brand
+ }
}
pub fn get_raw_times(p: &Processor) -> (u64, u64) {
(p.new_values.total_time(), p.old_values.total_time())
}
+
+pub fn get_cpu_frequency() -> u64 {
+ // /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq
+ let mut s = String::new();
+ if let Err(_) = File::open("/proc/cpuinfo").and_then(|mut f| f.read_to_string(&mut s)) {
+ return 0;
+ }
+
+ let find_cpu_mhz = s.split('\n').find(|line| {
+ line.starts_with("cpu MHz\t")
+ || line.starts_with("BogoMIPS")
+ || line.starts_with("clock\t")
+ || line.starts_with("bogomips per cpu")
+ });
+
+ find_cpu_mhz
+ .and_then(|line| line.split(':').last())
+ .and_then(|val| val.replace("MHz", "").trim().parse::<f64>().ok())
+ .map(|speed| speed as u64)
+ .unwrap_or_default()
+}
+
+/// Returns the brand/vendor string for the first CPU (which should be the same for all CPUs).
+pub fn get_vendor_id_and_brand() -> (String, String) {
+ let mut s = String::new();
+ if let Err(_) = File::open("/proc/cpuinfo").and_then(|mut f| f.read_to_string(&mut s)) {
+ return (String::new(), String::new());
+ }
+
+ fn get_value(s: &str) -> String {
+ s.split(':')
+ .last()
+ .map(|x| x.trim().to_owned())
+ .unwrap_or_default()
+ }
+
+ let mut vendor_id = None;
+ let mut brand = None;
+
+ for it in s.split('\n') {
+ if it.starts_with("vendor_id\t") {
+ vendor_id = Some(get_value(it));
+ } else if it.starts_with("model name\t") {
+ brand = Some(get_value(it));
+ } else {
+ continue;
+ }
+ if brand.is_some() && vendor_id.is_some() {
+ break;
+ }
+ }
+ (vendor_id.unwrap_or_default(), brand.unwrap_or_default())
+}
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -6,11 +6,12 @@
use sys::component::{self, Component};
use sys::disk;
-use sys::network;
use sys::process::*;
use sys::processor::*;
-use sys::Disk;
-use sys::NetworkData;
+
+use Disk;
+use LoadAvg;
+use Networks;
use Pid;
use {DiskExt, ProcessExt, RefreshKind, SystemExt};
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -106,7 +107,7 @@ pub struct System {
page_size_kb: u64,
temperatures: Vec<Component>,
disks: Vec<Disk>,
- network: NetworkData,
+ networks: Networks,
uptime: u64,
}
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -132,12 +133,64 @@ impl System {
}
fn refresh_processors(&mut self, limit: Option<u32>) {
+ fn get_callbacks(
+ first: bool,
+ ) -> Box<dyn Fn(&mut dyn Iterator<Item = &[u8]>, &mut Vec<Processor>, &mut usize)> {
+ if first {
+ let frequency = get_cpu_frequency();
+ let (vendor_id, brand) = get_vendor_id_and_brand();
+ Box::new(
+ move |parts: &mut dyn Iterator<Item = &[u8]>,
+ processors: &mut Vec<Processor>,
+ _| {
+ processors.push(Processor::new_with_values(
+ to_str!(parts.next().unwrap_or(&[])),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ frequency,
+ vendor_id.clone(),
+ brand.clone(),
+ ));
+ },
+ )
+ } else {
+ Box::new(
+ |parts: &mut dyn Iterator<Item = &[u8]>,
+ processors: &mut Vec<Processor>,
+ i: &mut usize| {
+ parts.next(); // we don't want the name again
+ processors[*i].set(
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ parts.next().map(|v| to_u64(v)).unwrap_or(0),
+ );
+ *i += 1;
+ },
+ )
+ }
+ }
if let Ok(f) = File::open("/proc/stat") {
let buf = BufReader::new(f);
let mut i = 0;
let first = self.processors.is_empty();
let mut it = buf.split(b'\n');
let mut count = 0;
+ let callback = get_callbacks(first);
while let Some(Ok(line)) = it.next() {
if &line[..3] != b"cpu" {
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -146,37 +199,7 @@ impl System {
count += 1;
let mut parts = line.split(|x| *x == b' ').filter(|s| !s.is_empty());
- if first {
- self.processors.push(new_processor(
- to_str!(parts.next().unwrap_or(&[])),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- ));
- } else {
- parts.next(); // we don't want the name again
- set_processor(
- &mut self.processors[i],
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- parts.next().map(|v| to_u64(v)).unwrap_or(0),
- );
- i += 1;
- }
+ callback(&mut parts, &mut self.processors, &mut i);
if let Some(limit) = limit {
if count >= limit {
break;
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -199,7 +222,7 @@ impl SystemExt for System {
page_size_kb: unsafe { sysconf(_SC_PAGESIZE) as u64 / 1024 },
temperatures: component::get_components(),
disks: Vec::with_capacity(2),
- network: network::new(),
+ networks: Networks::new(),
uptime: get_uptime(),
};
s.refresh_specifics(refreshes);
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -287,14 +310,10 @@ impl SystemExt for System {
}
}
- fn refresh_disk_list(&mut self) {
+ fn refresh_disks_list(&mut self) {
self.disks = get_all_disks();
}
- fn refresh_network(&mut self) {
- network::update_network(&mut self.network);
- }
-
// COMMON PART
//
// Need to be moved into a "common" file to avoid duplication.
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -307,8 +326,12 @@ impl SystemExt for System {
self.process_list.tasks.get(&pid)
}
- fn get_network(&self) -> &NetworkData {
- &self.network
+ fn get_networks(&self) -> &Networks {
+ &self.networks
+ }
+
+ fn get_networks_mut(&mut self) -> &mut Networks {
+ &mut self.networks
}
fn get_processor_list(&self) -> &[Processor] {
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -351,6 +374,24 @@ impl SystemExt for System {
fn get_uptime(&self) -> u64 {
self.uptime
}
+
+ fn get_load_average(&self) -> LoadAvg {
+ let mut s = String::new();
+ if let Err(_) = File::open("/proc/loadavg").and_then(|mut f| f.read_to_string(&mut s)) {
+ return LoadAvg::default();
+ }
+ let loads = s
+ .trim()
+ .split(' ')
+ .take(3)
+ .map(|val| val.parse::<f64>().unwrap())
+ .collect::<Vec<f64>>();
+ LoadAvg {
+ one: loads[0],
+ five: loads[1],
+ fifteen: loads[2],
+ }
+ }
}
impl Default for System {
diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs
--- a/src/mac/ffi.rs
+++ b/src/mac/ffi.rs
@@ -82,6 +82,14 @@ extern "C" {
//pub fn host_statistics(host_priv: u32, flavor: u32, host_info: *mut c_void,
// host_count: *const u32) -> u32;
pub fn vm_deallocate(target_task: u32, address: *mut i32, size: u32) -> kern_return_t;
+ pub fn sysctlbyname(
+ name: *const c_char,
+ oldp: *mut c_void,
+ oldlenp: *mut usize,
+ newp: *mut c_void,
+ newlen: usize,
+ ) -> kern_return_t;
+ pub fn getloadavg(loads: *const f64, size: c_int);
// pub fn proc_pidpath(pid: i32, buf: *mut i8, bufsize: u32) -> i32;
// pub fn proc_name(pid: i32, buf: *mut i8, bufsize: u32) -> i32;
diff --git a/src/mac/mod.rs b/src/mac/mod.rs
--- a/src/mac/mod.rs
+++ b/src/mac/mod.rs
@@ -14,7 +14,7 @@ pub mod system;
pub use self::component::Component;
pub use self::disk::{Disk, DiskType};
-pub use self::network::NetworkData;
+pub use self::network::{NetworkData, Networks};
pub use self::process::{Process, ProcessStatus};
pub use self::processor::Processor;
pub use self::system::System;
diff --git a/src/mac/network.rs b/src/mac/network.rs
--- a/src/mac/network.rs
+++ b/src/mac/network.rs
@@ -5,17 +5,126 @@
//
use libc::{self, c_char, CTL_NET, NET_RT_IFLIST2, PF_ROUTE, RTM_IFINFO2};
+
+use std::collections::HashMap;
use std::ptr::null_mut;
use sys::ffi;
use NetworkExt;
+use NetworksExt;
+use NetworksIter;
+
+/// Network interfaces.
+///
+/// ```no_run
+/// use sysinfo::{NetworksExt, System, SystemExt};
+///
+/// let s = System::new_all();
+/// let networks = s.get_networks();
+/// ```
+pub struct Networks {
+ interfaces: HashMap<String, NetworkData>,
+}
+
+impl Networks {
+ pub(crate) fn new() -> Self {
+ Networks {
+ interfaces: HashMap::new(),
+ }
+ }
+
+ #[allow(clippy::cast_ptr_alignment)]
+ fn update_networks(&mut self) {
+ let mib = &mut [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0];
+ let mut len = 0;
+ if unsafe { libc::sysctl(mib.as_mut_ptr(), 6, null_mut(), &mut len, null_mut(), 0) } < 0 {
+ // TODO: might be nice to put an error in here...
+ return;
+ }
+ let mut buf = Vec::with_capacity(len);
+ unsafe {
+ buf.set_len(len);
+ if libc::sysctl(
+ mib.as_mut_ptr(),
+ 6,
+ buf.as_mut_ptr(),
+ &mut len,
+ null_mut(),
+ 0,
+ ) < 0
+ {
+ // TODO: might be nice to put an error in here...
+ return;
+ }
+ }
+ let buf = buf.as_ptr() as *const c_char;
+ let lim = unsafe { buf.add(len) };
+ let mut next = buf;
+ while next < lim {
+ unsafe {
+ let ifm = next as *const libc::if_msghdr;
+ next = next.offset((*ifm).ifm_msglen as isize);
+ if (*ifm).ifm_type == RTM_IFINFO2 as u8 {
+ // The interface (line description) name stored at ifname will be returned in
+ // the default coded character set identifier (CCSID) currently in effect for
+ // the job. If this is not a single byte CCSID, then storage greater than
+ // IFNAMSIZ (16) bytes may be needed. 22 bytes is large enough for all CCSIDs.
+ let mut name = vec![0u8; libc::IFNAMSIZ + 6];
+
+ let if2m: *const ffi::if_msghdr2 = ifm as *const ffi::if_msghdr2;
+ let pname =
+ libc::if_indextoname((*if2m).ifm_index as _, name.as_mut_ptr() as _);
+ if pname.is_null() {
+ continue;
+ }
+ name.set_len(libc::strlen(pname));
+ let name = String::from_utf8_unchecked(name);
+ let ibytes = (*if2m).ifm_data.ifi_ibytes;
+ let obytes = (*if2m).ifm_data.ifi_obytes;
+ let interface = self.interfaces.entry(name).or_insert_with(|| NetworkData {
+ old_in: ibytes,
+ current_in: ibytes,
+ old_out: obytes,
+ current_out: obytes,
+ updated: true,
+ });
+ interface.old_in = interface.current_in;
+ interface.current_in = ibytes;
+ interface.old_out = interface.current_out;
+ interface.current_out = obytes;
+ interface.updated = true;
+ }
+ }
+ }
+ }
+}
+
+impl NetworksExt for Networks {
+ fn iter<'a>(&'a self) -> NetworksIter<'a> {
+ NetworksIter::new(self.interfaces.iter())
+ }
+
+ fn refresh_networks_list(&mut self) {
+ for (_, data) in self.interfaces.iter_mut() {
+ data.updated = false;
+ }
+ self.update_networks();
+ self.interfaces.retain(|_, data| data.updated);
+ }
+
+ fn refresh(&mut self) {
+ self.update_networks();
+ }
+}
/// Contains network information.
+#[derive(PartialEq, Eq)]
pub struct NetworkData {
old_in: u64,
old_out: u64,
current_in: u64,
current_out: u64,
+ updated: bool,
}
impl NetworkExt for NetworkData {
diff --git a/src/mac/network.rs b/src/mac/network.rs
--- a/src/mac/network.rs
+++ b/src/mac/network.rs
@@ -26,67 +135,12 @@ impl NetworkExt for NetworkData {
fn get_outcome(&self) -> u64 {
self.current_out - self.old_out
}
-}
-pub fn new() -> NetworkData {
- NetworkData {
- old_in: 0,
- old_out: 0,
- current_in: 0,
- current_out: 0,
+ fn get_total_income(&self) -> u64 {
+ self.current_in
}
-}
-#[allow(clippy::cast_ptr_alignment)]
-pub fn update_network(n: &mut NetworkData) {
- let mib = &mut [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0];
- let mut len = 0;
- if unsafe { libc::sysctl(mib.as_mut_ptr(), 6, null_mut(), &mut len, null_mut(), 0) } < 0 {
- // TODO: might be nice to put an error in here...
- return;
- }
- let mut buf = Vec::with_capacity(len);
- unsafe {
- buf.set_len(len);
- if libc::sysctl(
- mib.as_mut_ptr(),
- 6,
- buf.as_mut_ptr(),
- &mut len,
- null_mut(),
- 0,
- ) < 0
- {
- // TODO: might be nice to put an error in here...
- return;
- }
- }
- let buf = buf.as_ptr() as *const c_char;
- let lim = unsafe { buf.add(len) };
- let mut next = buf;
- let mut totalibytes = 0u64;
- let mut totalobytes = 0u64;
- while next < lim {
- unsafe {
- let ifm = next as *const libc::if_msghdr;
- next = next.offset((*ifm).ifm_msglen as isize);
- if (*ifm).ifm_type == RTM_IFINFO2 as u8 {
- let if2m: *const ffi::if_msghdr2 = ifm as *const ffi::if_msghdr2;
- totalibytes += (*if2m).ifm_data.ifi_ibytes;
- totalobytes += (*if2m).ifm_data.ifi_obytes;
- }
- }
+ fn get_total_outcome(&self) -> u64 {
+ self.current_out
}
- n.old_in = if n.current_in > totalibytes {
- 0
- } else {
- n.current_in
- };
- n.current_in = totalibytes;
- n.old_out = if n.current_out > totalibytes {
- 0
- } else {
- n.current_out
- };
- n.current_out = totalobytes;
}
diff --git a/src/mac/process.rs b/src/mac/process.rs
--- a/src/mac/process.rs
+++ b/src/mac/process.rs
@@ -152,11 +152,7 @@ pub struct Process {
}
impl Process {
- pub(crate) fn new_empty(
- pid: Pid,
- exe: PathBuf,
- name: String,
- ) -> Process {
+ pub(crate) fn new_empty(pid: Pid, exe: PathBuf, name: String) -> Process {
Process {
name,
pid,
diff --git a/src/mac/process.rs b/src/mac/process.rs
--- a/src/mac/process.rs
+++ b/src/mac/process.rs
@@ -435,7 +431,11 @@ pub(crate) fn update_process(
) != mem::size_of::<libc::proc_bsdinfo>() as _
{
let mut buffer: Vec<u8> = Vec::with_capacity(ffi::PROC_PIDPATHINFO_MAXSIZE as _);
- match ffi::proc_pidpath(pid, buffer.as_mut_ptr() as *mut _, ffi::PROC_PIDPATHINFO_MAXSIZE) {
+ match ffi::proc_pidpath(
+ pid,
+ buffer.as_mut_ptr() as *mut _,
+ ffi::PROC_PIDPATHINFO_MAXSIZE,
+ ) {
x if x > 0 => {
buffer.set_len(x as _);
let tmp = String::from_utf8_unchecked(buffer);
diff --git a/src/mac/processor.rs b/src/mac/processor.rs
--- a/src/mac/processor.rs
+++ b/src/mac/processor.rs
@@ -4,6 +4,7 @@
// Copyright (c) 2015 Guillaume Gomez
//
+use libc::c_char;
use std::ops::Deref;
use std::sync::Arc;
use sys::ffi;
diff --git a/src/mac/processor.rs b/src/mac/processor.rs
--- a/src/mac/processor.rs
+++ b/src/mac/processor.rs
@@ -54,16 +55,41 @@ pub struct Processor {
name: String,
cpu_usage: f32,
processor_data: Arc<ProcessorData>,
+ frequency: u64,
+ vendor_id: String,
+ brand: String,
}
impl Processor {
- fn new(name: String, processor_data: Arc<ProcessorData>) -> Processor {
+ pub(crate) fn new(
+ name: String,
+ processor_data: Arc<ProcessorData>,
+ frequency: u64,
+ vendor_id: String,
+ brand: String,
+ ) -> Processor {
Processor {
name,
cpu_usage: 0f32,
processor_data,
+ frequency,
+ vendor_id,
+ brand,
}
}
+
+ pub(crate) fn set_cpu_usage(&mut self, cpu_usage: f32) {
+ self.cpu_usage = cpu_usage;
+ }
+
+ pub(crate) fn update(&mut self, cpu_usage: f32, processor_data: Arc<ProcessorData>) {
+ self.cpu_usage = cpu_usage;
+ self.processor_data = processor_data;
+ }
+
+ pub(crate) fn get_data(&self) -> Arc<ProcessorData> {
+ Arc::clone(&self.processor_data)
+ }
}
impl ProcessorExt for Processor {
diff --git a/src/mac/processor.rs b/src/mac/processor.rs
--- a/src/mac/processor.rs
+++ b/src/mac/processor.rs
@@ -74,25 +100,75 @@ impl ProcessorExt for Processor {
fn get_name(&self) -> &str {
&self.name
}
-}
-pub fn set_cpu_usage(p: &mut Processor, usage: f32) {
- p.cpu_usage = usage;
-}
+ /// Returns the processor frequency in MHz.
+ fn get_frequency(&self) -> u64 {
+ self.frequency
+ }
-pub fn create_proc(name: String, processor_data: Arc<ProcessorData>) -> Processor {
- Processor::new(name, processor_data)
+ fn get_vendor_id(&self) -> &str {
+ &self.vendor_id
+ }
+
+ fn get_brand(&self) -> &str {
+ &self.brand
+ }
}
-pub fn update_proc(p: &mut Processor, cpu_usage: f32, processor_data: Arc<ProcessorData>) {
- p.cpu_usage = cpu_usage;
- p.processor_data = processor_data;
+pub fn get_cpu_frequency() -> u64 {
+ let mut speed: u64 = 0;
+ let mut len = std::mem::size_of::<u64>();
+ unsafe {
+ ffi::sysctlbyname(
+ b"hw.cpufrequency\0".as_ptr() as *const c_char,
+ &mut speed as *mut _ as _,
+ &mut len,
+ std::ptr::null_mut(),
+ 0,
+ );
+ }
+ speed /= 1000000;
+ speed
}
-pub fn set_cpu_proc(p: &mut Processor, cpu_usage: f32) {
- p.cpu_usage = cpu_usage;
+fn get_sysctl_str(s: &[u8]) -> String {
+ let mut len = 0;
+
+ unsafe {
+ ffi::sysctlbyname(
+ s.as_ptr() as *const c_char,
+ std::ptr::null_mut(),
+ &mut len,
+ std::ptr::null_mut(),
+ 0,
+ );
+ }
+ if len < 1 {
+ return String::new();
+ }
+ let mut buf = Vec::with_capacity(len);
+ unsafe {
+ ffi::sysctlbyname(
+ s.as_ptr() as *const c_char,
+ buf.as_mut_ptr() as _,
+ &mut len,
+ std::ptr::null_mut(),
+ 0,
+ );
+ }
+ if len > 0 {
+ unsafe {
+ buf.set_len(len);
+ }
+ String::from_utf8(buf).unwrap_or_else(|_| String::new())
+ } else {
+ String::new()
+ }
}
-pub fn get_processor_data(p: &Processor) -> Arc<ProcessorData> {
- Arc::clone(&p.processor_data)
+pub fn get_vendor_id_and_brand() -> (String, String) {
+ (
+ get_sysctl_str(b"machdep.cpu.brand_string\0"),
+ get_sysctl_str(b"machdep.cpu.vendor\0"),
+ )
}
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -7,17 +7,16 @@
use sys::component::Component;
use sys::disk::Disk;
use sys::ffi;
-use sys::network::{self, NetworkData};
+use sys::network::Networks;
use sys::process::*;
use sys::processor::*;
-use {DiskExt, Pid, ProcessExt, ProcessorExt, RefreshKind, SystemExt};
+use {DiskExt, LoadAvg, Pid, ProcessExt, ProcessorExt, RefreshKind, SystemExt};
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::mem;
use std::sync::Arc;
-use sys::processor;
use libc::{self, c_int, c_void, size_t, sysconf, _SC_PAGESIZE};
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -35,7 +34,7 @@ pub struct System {
temperatures: Vec<Component>,
connection: Option<ffi::io_connect_t>,
disks: Vec<Disk>,
- network: NetworkData,
+ networks: Networks,
uptime: u64,
port: ffi::mach_port_t,
}
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -83,7 +82,7 @@ impl SystemExt for System {
temperatures: Vec::with_capacity(2),
connection: get_io_service_connection(),
disks: Vec::with_capacity(1),
- network: network::new(),
+ networks: Networks::new(),
uptime: get_uptime(),
port: unsafe { ffi::mach_host_self() },
};
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -183,6 +182,8 @@ impl SystemExt for System {
if self.processors.is_empty() {
let mut num_cpu = 0;
+ let (vendor_id, brand) = get_vendor_id_and_brand();
+ let frequency = get_cpu_frequency();
if !get_sys_value(
ffi::CTL_HW,
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -194,9 +195,12 @@ impl SystemExt for System {
num_cpu = 1;
}
- self.processors.push(processor::create_proc(
+ self.processors.push(Processor::new(
"0".to_owned(),
Arc::new(ProcessorData::new(::std::ptr::null_mut(), 0)),
+ frequency,
+ vendor_id.clone(),
+ brand.clone(),
));
if ffi::host_processor_info(
self.port,
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -208,8 +212,13 @@ impl SystemExt for System {
{
let proc_data = Arc::new(ProcessorData::new(cpu_info, num_cpu_info));
for i in 0..num_cpu {
- let mut p =
- processor::create_proc(format!("{}", i + 1), Arc::clone(&proc_data));
+ let mut p = Processor::new(
+ format!("{}", i + 1),
+ Arc::clone(&proc_data),
+ frequency,
+ vendor_id.clone(),
+ brand.clone(),
+ );
let in_use = *cpu_info.offset(
(ffi::CPU_STATE_MAX * i) as isize + ffi::CPU_STATE_USER as isize,
) + *cpu_info.offset(
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -221,7 +230,7 @@ impl SystemExt for System {
+ *cpu_info.offset(
(ffi::CPU_STATE_MAX * i) as isize + ffi::CPU_STATE_IDLE as isize,
);
- processor::set_cpu_proc(&mut p, in_use as f32 / total as f32);
+ p.set_cpu_usage(in_use as f32 / total as f32);
self.processors.push(p);
}
}
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -236,7 +245,7 @@ impl SystemExt for System {
let mut pourcent = 0f32;
let proc_data = Arc::new(ProcessorData::new(cpu_info, num_cpu_info));
for (i, proc_) in self.processors.iter_mut().skip(1).enumerate() {
- let old_proc_data = &*processor::get_processor_data(proc_);
+ let old_proc_data = &*proc_.get_data();
let in_use =
(*cpu_info.offset(
(ffi::CPU_STATE_MAX * i) as isize + ffi::CPU_STATE_USER as isize,
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -257,27 +266,19 @@ impl SystemExt for System {
) - *old_proc_data.cpu_info.offset(
(ffi::CPU_STATE_MAX * i) as isize + ffi::CPU_STATE_IDLE as isize,
));
- processor::update_proc(
- proc_,
- in_use as f32 / total as f32,
- Arc::clone(&proc_data),
- );
+ proc_.update(in_use as f32 / total as f32, Arc::clone(&proc_data));
pourcent += proc_.get_cpu_usage();
}
if self.processors.len() > 1 {
let len = self.processors.len() - 1;
if let Some(p) = self.processors.get_mut(0) {
- processor::set_cpu_usage(p, pourcent / len as f32);
+ p.set_cpu_usage(pourcent / len as f32);
}
}
}
}
}
- fn refresh_network(&mut self) {
- network::update_network(&mut self.network);
- }
-
fn refresh_processes(&mut self) {
let count = unsafe { ffi::proc_listallpids(::std::ptr::null_mut(), 0) };
if count < 1 {
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -288,15 +289,9 @@ impl SystemExt for System {
let entries: Vec<Process> = {
let wrap = &Wrap(UnsafeCell::new(&mut self.process_list));
pids.par_iter()
- .flat_map(|pid| {
- match update_process(
- wrap,
- *pid,
- arg_max as size_t,
- ) {
- Ok(x) => x,
- Err(_) => None,
- }
+ .flat_map(|pid| match update_process(wrap, *pid, arg_max as size_t) {
+ Ok(x) => x,
+ Err(_) => None,
})
.collect()
};
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -311,11 +306,7 @@ impl SystemExt for System {
let arg_max = get_arg_max();
match {
let wrap = Wrap(UnsafeCell::new(&mut self.process_list));
- update_process(
- &wrap,
- pid,
- arg_max as size_t,
- )
+ update_process(&wrap, pid, arg_max as size_t)
} {
Ok(Some(p)) => {
self.process_list.insert(p.pid(), p);
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -332,7 +323,7 @@ impl SystemExt for System {
}
}
- fn refresh_disk_list(&mut self) {
+ fn refresh_disks_list(&mut self) {
self.disks = crate::mac::disk::get_disks();
}
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -352,8 +343,12 @@ impl SystemExt for System {
&self.processors[..]
}
- fn get_network(&self) -> &NetworkData {
- &self.network
+ fn get_networks(&self) -> &Networks {
+ &self.networks
+ }
+
+ fn get_networks_mut(&mut self) -> &mut Networks {
+ &mut self.networks
}
fn get_total_memory(&self) -> u64 {
diff --git a/src/mac/system.rs b/src/mac/system.rs
--- a/src/mac/system.rs
+++ b/src/mac/system.rs
@@ -392,6 +387,18 @@ impl SystemExt for System {
fn get_uptime(&self) -> u64 {
self.uptime
}
+
+ fn get_load_average(&self) -> LoadAvg {
+ let loads = vec![0f64; 3];
+ unsafe {
+ ffi::getloadavg(loads.as_ptr() as *const f64, 3);
+ }
+ LoadAvg {
+ one: loads[0],
+ five: loads[1],
+ fifteen: loads[2],
+ }
+ }
}
impl Default for System {
diff --git a/src/sysinfo.rs b/src/sysinfo.rs
--- a/src/sysinfo.rs
+++ b/src/sysinfo.rs
@@ -78,9 +78,13 @@ cfg_if! {
}
}
-pub use common::{AsU32, Pid, RefreshKind};
-pub use sys::{Component, Disk, DiskType, NetworkData, Process, ProcessStatus, Processor, System};
-pub use traits::{ComponentExt, DiskExt, NetworkExt, ProcessExt, ProcessorExt, SystemExt};
+pub use common::{AsU32, NetworksIter, Pid, RefreshKind};
+pub use sys::{
+ Component, Disk, DiskType, NetworkData, Networks, Process, ProcessStatus, Processor, System,
+};
+pub use traits::{
+ ComponentExt, DiskExt, NetworkExt, NetworksExt, ProcessExt, ProcessorExt, SystemExt,
+};
#[cfg(feature = "c-interface")]
pub use c_interface::*;
diff --git a/src/sysinfo.rs b/src/sysinfo.rs
--- a/src/sysinfo.rs
+++ b/src/sysinfo.rs
@@ -102,26 +106,26 @@ mod utils;
/// a maximum number of files open equivalent to half of the system limit.
///
/// The problem is that some users might need all the available file descriptors so we need to
-/// allow them to change this limit. Reducing
+/// allow them to change this limit. Reducing
///
/// Note that if you set a limit bigger than the system limit, the system limit will be set.
///
/// Returns `true` if the new value has been set.
-pub fn set_open_files_limit(mut new_limit: isize) -> bool {
+pub fn set_open_files_limit(mut _new_limit: isize) -> bool {
#[cfg(all(not(target_os = "macos"), unix))]
{
- if new_limit < 0 {
- new_limit = 0;
+ if _new_limit < 0 {
+ _new_limit = 0;
}
let max = sys::system::get_max_nb_fds();
- if new_limit > max {
- new_limit = max;
+ if _new_limit > max {
+ _new_limit = max;
}
return if let Ok(ref mut x) = unsafe { sys::system::REMAINING_FILES.lock() } {
// If files are already open, to be sure that the number won't be bigger when those
// files are closed, we subtract the current number of opened files to the new limit.
let diff = max - **x;
- **x = new_limit - diff;
+ **x = _new_limit - diff;
true
} else {
false
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -4,7 +4,9 @@
// Copyright (c) 2017 Guillaume Gomez
//
-use sys::{Component, Disk, DiskType, NetworkData, Process, Processor};
+use sys::{Component, Disk, DiskType, Networks, Process, Processor};
+use LoadAvg;
+use NetworksIter;
use Pid;
use ProcessStatus;
use RefreshKind;
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -14,26 +16,90 @@ use std::ffi::OsStr;
use std::path::Path;
/// Contains all the methods of the `Disk` struct.
+///
+/// ```no_run
+/// use sysinfo::{DiskExt, System, SystemExt};
+///
+/// let s = System::new();
+/// for disk in s.get_disks() {
+/// println!("{:?}: {:?}", disk.get_name(), disk.get_type());
+/// }
+/// ```
pub trait DiskExt {
/// Returns the disk type.
+ ///
+ /// ```no_run
+ /// use sysinfo::{DiskExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for disk in s.get_disks() {
+ /// println!("{:?}", disk.get_type());
+ /// }
+ /// ```
fn get_type(&self) -> DiskType;
/// Returns the disk name.
+ ///
+ /// ```no_run
+ /// use sysinfo::{DiskExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for disk in s.get_disks() {
+ /// println!("{:?}", disk.get_name());
+ /// }
+ /// ```
fn get_name(&self) -> &OsStr;
/// Returns the file system used on this disk (so for example: `EXT4`, `NTFS`, etc...).
+ ///
+ /// ```no_run
+ /// use sysinfo::{DiskExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for disk in s.get_disks() {
+ /// println!("{:?}", disk.get_file_system());
+ /// }
+ /// ```
fn get_file_system(&self) -> &[u8];
/// Returns the mount point of the disk (`/` for example).
+ ///
+ /// ```no_run
+ /// use sysinfo::{DiskExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for disk in s.get_disks() {
+ /// println!("{:?}", disk.get_mount_point());
+ /// }
+ /// ```
fn get_mount_point(&self) -> &Path;
/// Returns the total disk size, in bytes.
+ ///
+ /// ```no_run
+ /// use sysinfo::{DiskExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for disk in s.get_disks() {
+ /// println!("{}", disk.get_total_space());
+ /// }
+ /// ```
fn get_total_space(&self) -> u64;
/// Returns the available disk size, in bytes.
+ ///
+ /// ```no_run
+ /// use sysinfo::{DiskExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for disk in s.get_disks() {
+ /// println!("{}", disk.get_available_space());
+ /// }
+ /// ```
fn get_available_space(&self) -> u64;
/// Update the disk' information.
+ #[doc(hidden)]
fn update(&mut self) -> bool;
}
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -42,56 +108,183 @@ pub trait ProcessExt {
/// Create a new process only containing the given information.
///
/// On windows, the `start_time` argument is ignored.
+ #[doc(hidden)]
fn new(pid: Pid, parent: Option<Pid>, start_time: u64) -> Self;
/// Sends the given `signal` to the process.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, Signal, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// process.kill(Signal::Kill);
+ /// }
+ /// ```
fn kill(&self, signal: ::Signal) -> bool;
/// Returns the name of the process.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{}", process.name());
+ /// }
+ /// ```
fn name(&self) -> &str;
/// Returns the command line.
// ///
// /// On Windows, this is always a one element vector.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{:?}", process.cmd());
+ /// }
+ /// ```
fn cmd(&self) -> &[String];
/// Returns the path to the process.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{}", process.exe().display());
+ /// }
+ /// ```
fn exe(&self) -> &Path;
/// Returns the pid of the process.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{}", process.pid());
+ /// }
+ /// ```
fn pid(&self) -> Pid;
/// Returns the environment of the process.
///
- /// Always empty on Windows except for current process.
+ /// Always empty on Windows, except for current process.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{:?}", process.environ());
+ /// }
+ /// ```
fn environ(&self) -> &[String];
/// Returns the current working directory.
///
/// Always empty on Windows.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{}", process.cwd().display());
+ /// }
+ /// ```
fn cwd(&self) -> &Path;
/// Returns the path of the root directory.
///
/// Always empty on Windows.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{}", process.root().display());
+ /// }
+ /// ```
fn root(&self) -> &Path;
/// Returns the memory usage (in KiB).
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{} KiB", process.memory());
+ /// }
+ /// ```
fn memory(&self) -> u64;
/// Returns the virtual memory usage (in KiB).
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{} KiB", process.virtual_memory());
+ /// }
+ /// ```
fn virtual_memory(&self) -> u64;
/// Returns the parent pid.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{:?}", process.parent());
+ /// }
+ /// ```
fn parent(&self) -> Option<Pid>;
/// Returns the status of the processus.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{:?}", process.status());
+ /// }
+ /// ```
fn status(&self) -> ProcessStatus;
/// Returns the time of process launch (in seconds).
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{}", process.start_time());
+ /// }
+ /// ```
fn start_time(&self) -> u64;
- /// Returns the total CPU usage.
+ /// Returns the total CPU usage (in %).
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{}%", process.cpu_usage());
+ /// }
+ /// ```
fn cpu_usage(&self) -> f32;
}
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -101,24 +294,93 @@ pub trait ProcessorExt {
///
/// Note: You'll need to refresh it at least twice at first if you want to have a
/// non-zero value.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessorExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for processor in s.get_processor_list() {
+ /// println!("{}%", processor.get_cpu_usage());
+ /// }
+ /// ```
fn get_cpu_usage(&self) -> f32;
/// Returns this processor's name.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessorExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for processor in s.get_processor_list() {
+ /// println!("{}", processor.get_name());
+ /// }
+ /// ```
fn get_name(&self) -> &str;
+
+ /// Returns the processor's vendor id.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessorExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for processor in s.get_processor_list() {
+ /// println!("{}", processor.get_vendor_id());
+ /// }
+ /// ```
+ fn get_vendor_id(&self) -> &str;
+
+ /// Returns the processor's brand.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessorExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for processor in s.get_processor_list() {
+ /// println!("{}", processor.get_brand());
+ /// }
+ /// ```
+ fn get_brand(&self) -> &str;
+
+ /// Returns the processor's frequency.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessorExt, System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// for processor in s.get_processor_list() {
+ /// println!("{}", processor.get_frequency());
+ /// }
+ /// ```
+ fn get_frequency(&self) -> u64;
}
/// Contains all the methods of the [`System`] type.
pub trait SystemExt: Sized {
- /// Creates a new [`System`] instance. It only contains the disks' list and the processes list
- /// at this stage. Use the [`refresh_all`] method to update its internal information (or any of
- /// the `refresh_` method).
+ /// Creates a new [`System`] instance with nothing loaded. Use the [`refresh_all`] method to
+ /// update its internal information (or any of the `refresh_` method).
///
/// [`refresh_all`]: #method.refresh_all
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new();
+ /// ```
fn new() -> Self {
- let mut s = Self::new_with_specifics(RefreshKind::new());
- s.refresh_disk_list();
- s.refresh_all();
- s
+ Self::new_with_specifics(RefreshKind::new())
+ }
+
+ /// Creates a new [`System`] instance with everything loaded.
+ ///
+ /// It is an equivalent of `SystemExt::new_with_specifics(RefreshKind::everything())`.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// ```
+ fn new_all() -> Self {
+ Self::new_with_specifics(RefreshKind::everything())
}
/// Creates a new [`System`] instance and refresh the data corresponding to the
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -130,14 +392,14 @@ pub trait SystemExt: Sized {
/// use sysinfo::{RefreshKind, System, SystemExt};
///
/// // We want everything except disks.
- /// let mut system = System::new_with_specifics(RefreshKind::everything().without_disk_list());
+ /// let mut system = System::new_with_specifics(RefreshKind::everything().without_disks_list());
///
/// assert_eq!(system.get_disks().len(), 0);
/// assert!(system.get_process_list().len() > 0);
///
/// // If you want the disks list afterwards, just call the corresponding
- /// // "refresh_disk_list":
- /// system.refresh_disk_list();
+ /// // "refresh_disks_list":
+ /// system.refresh_disks_list();
/// let disks = system.get_disks();
/// ```
fn new_with_specifics(refreshes: RefreshKind) -> Self;
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -150,10 +412,10 @@ pub trait SystemExt: Sized {
/// ```
/// use sysinfo::{RefreshKind, System, SystemExt};
///
- /// let mut s = System::new();
+ /// let mut s = System::new_all();
///
- /// // Let's just update network data and processes:
- /// s.refresh_specifics(RefreshKind::new().with_network().with_processes());
+ /// // Let's just update networks and processes:
+ /// s.refresh_specifics(RefreshKind::new().with_networks().with_processes());
/// ```
fn refresh_specifics(&mut self, refreshes: RefreshKind) {
if refreshes.memory() {
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -165,14 +427,17 @@ pub trait SystemExt: Sized {
if refreshes.temperatures() {
self.refresh_temperatures();
}
- if refreshes.network() {
- self.refresh_network();
+ if refreshes.networks_list() {
+ self.refresh_networks_list();
+ }
+ if refreshes.networks() {
+ self.refresh_networks();
}
if refreshes.processes() {
self.refresh_processes();
}
- if refreshes.disk_list() {
- self.refresh_disk_list();
+ if refreshes.disks_list() {
+ self.refresh_disks_list();
}
if refreshes.disks() {
self.refresh_disks();
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -187,6 +452,13 @@ pub trait SystemExt: Sized {
/// [`refresh_memory`]: SystemExt::refresh_memory
/// [`refresh_cpu`]: SystemExt::refresh_memory
/// [`refresh_temperatures`]: SystemExt::refresh_temperatures
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_system();
+ /// ```
fn refresh_system(&mut self) {
self.refresh_memory();
self.refresh_cpu();
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -194,45 +466,172 @@ pub trait SystemExt: Sized {
}
/// Refresh RAM and SWAP usage.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_memory();
+ /// ```
fn refresh_memory(&mut self);
/// Refresh CPU usage.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_cpu();
+ /// ```
fn refresh_cpu(&mut self);
/// Refresh components' temperature.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_temperatures();
+ /// ```
fn refresh_temperatures(&mut self);
/// Get all processes and update their information.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_processes();
+ /// ```
fn refresh_processes(&mut self);
/// Refresh *only* the process corresponding to `pid`. Returns `false` if the process doesn't
- /// exist.
+ /// exist or isn't listed.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_process(1337);
+ /// ```
fn refresh_process(&mut self, pid: Pid) -> bool;
/// Refreshes the listed disks' information.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_disks();
+ /// ```
fn refresh_disks(&mut self);
/// The disk list will be emptied then completely recomputed.
- fn refresh_disk_list(&mut self);
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_disks_list();
+ /// ```
+ fn refresh_disks_list(&mut self);
- /// Refresh data network.
- fn refresh_network(&mut self);
+ /// Refresh networks data.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_networks();
+ /// ```
+ ///
+ /// It is a shortcut for:
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworksExt, System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// let networks = s.get_networks_mut();
+ /// networks.refresh();
+ /// ```
+ fn refresh_networks(&mut self) {
+ self.get_networks_mut().refresh();
+ }
+
+ /// The network list will be emptied then completely recomputed.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_networks_list();
+ /// ```
+ ///
+ /// This is a shortcut for:
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworksExt, System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// let networks = s.get_networks_mut();
+ /// networks.refresh_networks_list();
+ /// ```
+ fn refresh_networks_list(&mut self) {
+ self.get_networks_mut().refresh_networks_list();
+ }
- /// Refreshes all system, processes and disks information.
+ /// Refreshes all system, processes, disks and network interfaces information.
+ ///
+ /// Please note that it doesn't recompute disks list, components list nor network interfaces
+ /// list.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// s.refresh_all();
+ /// ```
fn refresh_all(&mut self) {
self.refresh_system();
self.refresh_processes();
self.refresh_disks();
- self.refresh_network();
+ self.refresh_networks();
}
/// Returns the process list.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// for (pid, process) in s.get_process_list() {
+ /// println!("{} {}", pid, process.name());
+ /// }
+ /// ```
fn get_process_list(&self) -> &HashMap<Pid, Process>;
/// Returns the process corresponding to the given pid or `None` if no such process exists.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// if let Some(process) = s.get_process(1337) {
+ /// println!("{}", process.name());
+ /// }
+ /// ```
fn get_process(&self, pid: Pid) -> Option<&Process>;
/// Returns a list of process containing the given `name`.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// for process in s.get_process_by_name("htop") {
+ /// println!("{} {}", process.pid(), process.name());
+ /// }
+ /// ```
fn get_process_by_name(&self, name: &str) -> Vec<&Process> {
let mut ret = vec![];
for val in self.get_process_list().values() {
diff --git a/src/traits.rs b/src/traits.rs
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -244,56 +643,292 @@ pub trait SystemExt: Sized {
}
/// The first processor in the array is the "main" one (aka the addition of all the others).
+ ///
+ /// ```no_run
+ /// use sysinfo::{ProcessorExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// for processor in s.get_processor_list() {
+ /// println!("{}%", processor.get_cpu_usage());
+ /// }
+ /// ```
fn get_processor_list(&self) -> &[Processor];
/// Returns total RAM size in KiB.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// println!("{} KiB", s.get_total_memory());
+ /// ```
fn get_total_memory(&self) -> u64;
/// Returns free RAM size in KiB.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// println!("{} KiB", s.get_free_memory());
+ /// ```
fn get_free_memory(&self) -> u64;
/// Returns used RAM size in KiB.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// println!("{} KiB", s.get_used_memory());
+ /// ```
fn get_used_memory(&self) -> u64;
/// Returns SWAP size in KiB.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// println!("{} KiB", s.get_total_swap());
+ /// ```
fn get_total_swap(&self) -> u64;
/// Returns free SWAP size in KiB.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// println!("{} KiB", s.get_free_swap());
+ /// ```
fn get_free_swap(&self) -> u64;
/// Returns used SWAP size in KiB.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// println!("{} KiB", s.get_used_swap());
+ /// ```
fn get_used_swap(&self) -> u64;
/// Returns components list.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ComponentExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// for component in s.get_components_list() {
+ /// println!("{}: {}°C", component.get_label(), component.get_temperature());
+ /// }
+ /// ```
fn get_components_list(&self) -> &[Component];
/// Returns disks' list.
+ ///
+ /// ```no_run
+ /// use sysinfo::{DiskExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// for disk in s.get_disks() {
+ /// println!("{:?}", disk.get_name());
+ /// }
+ /// ```
fn get_disks(&self) -> &[Disk];
- /// Returns network data.
- fn get_network(&self) -> &NetworkData;
+ /// Returns network interfaces.
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// let networks = s.get_networks();
+ /// for (interface_name, data) in networks {
+ /// println!("[{}] in: {}, out: {}", interface_name, data.get_income(), data.get_outcome());
+ /// }
+ /// ```
+ fn get_networks(&self) -> &Networks;
+
+ /// Returns a mutable access to network interfaces.
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// let networks = s.get_networks_mut();
+ /// networks.refresh_networks_list();
+ /// ```
+ fn get_networks_mut(&mut self) -> &mut Networks;
/// Returns system uptime.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// println!("{}", s.get_uptime());
+ /// ```
fn get_uptime(&self) -> u64;
+
+ /// Returns the system load average value.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// let load_avg = s.get_load_average();
+ /// println!(
+ /// "one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
+ /// load_avg.one,
+ /// load_avg.five,
+ /// load_avg.fifteen,
+ /// );
+ /// ```
+ fn get_load_average(&self) -> LoadAvg;
}
/// Getting volume of incoming and outgoing data.
pub trait NetworkExt {
- /// Returns the number of incoming bytes.
+ /// Returns the number of incoming bytes since the last refresh.
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// let networks = s.get_networks();
+ /// for (interface_name, network) in networks {
+ /// println!("in: {} B", network.get_income());
+ /// }
+ /// ```
fn get_income(&self) -> u64;
- /// Returns the number of outgoing bytes.
+ /// Returns the number of outgoing bytes since the last refresh.
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// let networks = s.get_networks();
+ /// for (interface_name, network) in networks {
+ /// println!("in: {} B", network.get_outcome());
+ /// }
+ /// ```
fn get_outcome(&self) -> u64;
+
+ /// Returns the total number of incoming bytes.
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// let networks = s.get_networks();
+ /// for (interface_name, network) in networks {
+ /// println!("in: {} B", network.get_total_income());
+ /// }
+ /// ```
+ fn get_total_income(&self) -> u64;
+
+ /// Returns the total number of outgoing bytes.
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// let networks = s.get_networks();
+ /// for (interface_name, network) in networks {
+ /// println!("in: {} B", network.get_total_outcome());
+ /// }
+ /// ```
+ fn get_total_outcome(&self) -> u64;
+}
+
+/// Interacting with network interfaces.
+pub trait NetworksExt {
+ /// Returns an iterator over the network interfaces.
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// let networks = s.get_networks();
+ /// for (interface_name, network) in networks {
+ /// println!("in: {} B", network.get_income());
+ /// }
+ /// ```
+ fn iter(&self) -> NetworksIter;
+
+ /// Refreshes the network interfaces list.
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworksExt, System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// let networks = s.get_networks_mut();
+ /// networks.refresh_networks_list();
+ /// ```
+ fn refresh_networks_list(&mut self);
+
+ /// Refreshes the network interfaces' content.
+ ///
+ /// ```no_run
+ /// use sysinfo::{NetworksExt, System, SystemExt};
+ ///
+ /// let mut s = System::new_all();
+ /// let networks = s.get_networks_mut();
+ /// networks.refresh();
+ /// ```
+ fn refresh(&mut self);
}
/// Getting a component temperature information.
pub trait ComponentExt {
/// Returns the component's temperature (in celsius degree).
+ ///
+ /// ```no_run
+ /// use sysinfo::{ComponentExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// for component in s.get_components_list() {
+ /// println!("{}°C", component.get_temperature());
+ /// }
+ /// ```
fn get_temperature(&self) -> f32;
+
/// Returns the maximum temperature of this component.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ComponentExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// for component in s.get_components_list() {
+ /// println!("{}°C", component.get_max());
+ /// }
+ /// ```
fn get_max(&self) -> f32;
+
/// Returns the highest temperature before the computer halts.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ComponentExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// for component in s.get_components_list() {
+ /// println!("{:?}°C", component.get_critical());
+ /// }
+ /// ```
fn get_critical(&self) -> Option<f32>;
+
/// Returns component's label.
+ ///
+ /// ```no_run
+ /// use sysinfo::{ComponentExt, System, SystemExt};
+ ///
+ /// let s = System::new_all();
+ /// for component in s.get_components_list() {
+ /// println!("{}", component.get_label());
+ /// }
+ /// ```
fn get_label(&self) -> &str;
}
diff --git a/src/unknown/mod.rs b/src/unknown/mod.rs
--- a/src/unknown/mod.rs
+++ b/src/unknown/mod.rs
@@ -13,7 +13,7 @@ pub mod system;
pub use self::component::Component;
pub use self::disk::{Disk, DiskType};
-pub use self::network::NetworkData;
+pub use self::network::{Networks, NetworkData};
pub use self::process::{Process, ProcessStatus};
pub use self::processor::Processor;
pub use self::system::System;
diff --git a/src/unknown/network.rs b/src/unknown/network.rs
--- a/src/unknown/network.rs
+++ b/src/unknown/network.rs
@@ -4,7 +4,41 @@
// Copyright (c) 2017 Guillaume Gomez
//
+use std::collections::HashMap;
+
use NetworkExt;
+use NetworksExt;
+use NetworksIter;
+
+/// Network interfaces.
+///
+/// ```no_run
+/// use sysinfo::{NetworksExt, System, SystemExt};
+///
+/// let s = System::new_all();
+/// let networks = s.get_networks();
+/// ```
+pub struct Networks {
+ interfaces: HashMap<String, NetworkData>,
+}
+
+impl Networks {
+ pub(crate) fn new() -> Networks {
+ Networks {
+ interfaces: HashMap::new(),
+ }
+ }
+}
+
+impl NetworksExt for Networks {
+ fn iter<'a>(&'a self) -> NetworksIter<'a> {
+ NetworksIter::new(self.interfaces.iter())
+ }
+
+ fn refresh_networks_list(&mut self) {}
+
+ fn refresh(&mut self) {}
+}
/// Contains network information.
#[derive(Debug)]
diff --git a/src/unknown/network.rs b/src/unknown/network.rs
--- a/src/unknown/network.rs
+++ b/src/unknown/network.rs
@@ -18,4 +52,12 @@ impl NetworkExt for NetworkData {
fn get_outcome(&self) -> u64 {
0
}
+
+ fn get_total_income(&self) -> u64 {
+ 0
+ }
+
+ fn get_total_outcome(&self) -> u64 {
+ 0
+ }
}
diff --git a/src/unknown/processor.rs b/src/unknown/processor.rs
--- a/src/unknown/processor.rs
+++ b/src/unknown/processor.rs
@@ -4,6 +4,9 @@
// Copyright (c) 2015 Guillaume Gomez
//
+use std::default::Default;
+
+use LoadAvg;
use ProcessorExt;
/// Dummy struct that represents a processor.
diff --git a/src/unknown/processor.rs b/src/unknown/processor.rs
--- a/src/unknown/processor.rs
+++ b/src/unknown/processor.rs
@@ -17,4 +20,16 @@ impl ProcessorExt for Processor {
fn get_name(&self) -> &str {
""
}
+
+ fn get_frequency(&self) -> u64 {
+ 0
+ }
+
+ fn get_vendor_id(&self) -> &str {
+ ""
+ }
+
+ fn get_brand(&self) -> &str {
+ ""
+ }
}
diff --git a/src/unknown/system.rs b/src/unknown/system.rs
--- a/src/unknown/system.rs
+++ b/src/unknown/system.rs
@@ -8,7 +8,7 @@ use sys::component::Component;
use sys::process::*;
use sys::processor::*;
use sys::Disk;
-use sys::NetworkData;
+use sys::Networks;
use Pid;
use {RefreshKind, SystemExt};
diff --git a/src/unknown/system.rs b/src/unknown/system.rs
--- a/src/unknown/system.rs
+++ b/src/unknown/system.rs
@@ -18,14 +18,14 @@ use std::collections::HashMap;
#[derive(Debug)]
pub struct System {
processes_list: HashMap<Pid, Process>,
- network: NetworkData,
+ networks: Networks,
}
impl SystemExt for System {
fn new_with_specifics(_: RefreshKind) -> System {
System {
processes_list: Default::default(),
- network: NetworkData,
+ networks: Networks::new(),
}
}
diff --git a/src/unknown/system.rs b/src/unknown/system.rs
--- a/src/unknown/system.rs
+++ b/src/unknown/system.rs
@@ -43,7 +43,7 @@ impl SystemExt for System {
fn refresh_disks(&mut self) {}
- fn refresh_disk_list(&mut self) {}
+ fn refresh_disks_list(&mut self) {}
fn refresh_network(&mut self) {}
diff --git a/src/unknown/system.rs b/src/unknown/system.rs
--- a/src/unknown/system.rs
+++ b/src/unknown/system.rs
@@ -59,8 +59,12 @@ impl SystemExt for System {
None
}
- fn get_network(&self) -> &NetworkData {
- &self.network
+ fn get_networks(&self) -> &Networks {
+ &self.networks
+ }
+
+ fn get_networks_mut(&mut self) -> &mut Networks {
+ &mut self.networks
}
fn get_processor_list(&self) -> &[Processor] {
diff --git a/src/unknown/system.rs b/src/unknown/system.rs
--- a/src/unknown/system.rs
+++ b/src/unknown/system.rs
@@ -102,6 +106,14 @@ impl SystemExt for System {
fn get_uptime(&self) -> u64 {
0
}
+
+ fn get_load_average(&self) -> LoadAvg {
+ LoadAvg {
+ one: 0.,
+ five: 0.,
+ fifteen: 0.,
+ }
+ }
}
impl Default for System {
diff --git a/src/windows/ffi.rs b/src/windows/ffi.rs
--- a/src/windows/ffi.rs
+++ b/src/windows/ffi.rs
@@ -1,333 +1,220 @@
-//
+//
// Sysinfo
-//
-// Copyright (c) 2015 Guillaume Gomez
+//
+// Copyright (c) 2020 Guillaume Gomez
//
-use libc::{c_int, c_char, c_void, c_uchar, c_uint, size_t, uint32_t, uint64_t, c_ushort};
-
-extern "C" {
- pub static kCFAllocatorDefault: CFAllocatorRef;
-
- pub fn proc_pidinfo(pid: c_int, flavor: c_int, arg: u64, buffer: *mut c_void,
- buffersize: c_int) -> c_int;
- pub fn proc_listallpids(buffer: *mut c_void, buffersize: c_int) -> c_int;
- //pub fn proc_name(pid: c_int, buffer: *mut c_void, buffersize: u32) -> c_int;
- //pub fn proc_regionfilename(pid: c_int, address: u64, buffer: *mut c_void,
- // buffersize: u32) -> c_int;
- //pub fn proc_pidpath(pid: c_int, buffer: *mut c_void, buffersize: u32) -> c_int;
-
- pub fn IOMasterPort(a: i32, b: *mut mach_port_t) -> i32;
- pub fn IOServiceMatching(a: *const c_char) -> *mut c_void;
- pub fn IOServiceGetMatchingServices(a: mach_port_t, b: *mut c_void, c: *mut io_iterator_t) -> i32;
- pub fn IOIteratorNext(iterator: io_iterator_t) -> io_object_t;
- pub fn IOObjectRelease(obj: io_object_t) -> i32;
- pub fn IOServiceOpen(device: io_object_t, a: u32, t: u32, x: *mut io_connect_t) -> i32;
- pub fn IOServiceClose(a: io_connect_t) -> i32;
- pub fn IOConnectCallStructMethod(connection: mach_port_t,
- selector: u32,
- inputStruct: *mut KeyData_t,
- inputStructCnt: size_t,
- outputStruct: *mut KeyData_t,
- outputStructCnt: *mut size_t) -> i32;
- pub fn IORegistryEntryCreateCFProperties(entry: io_registry_entry_t,
- properties: *mut CFMutableDictionaryRef,
- allocator: CFAllocatorRef,
- options: IOOptionBits)
- -> kern_return_t;
- pub fn CFDictionaryContainsKey(d: CFDictionaryRef, key: *const c_void) -> Boolean;
- pub fn CFDictionaryGetValue(d: CFDictionaryRef, key: *const c_void) -> *const c_void;
- pub fn IORegistryEntryGetName(entry: io_registry_entry_t, name: *mut c_char) -> kern_return_t;
- pub fn CFRelease(cf: CFTypeRef);
- pub fn CFStringCreateWithCStringNoCopy(alloc: *mut c_void, cStr: *const c_char,
- encoding: CFStringEncoding,
- contentsDeallocator: *mut c_void) -> CFStringRef;
-
- pub static kCFAllocatorNull: CFAllocatorRef;
-
- pub fn mach_absolute_time() -> u64;
- //pub fn task_for_pid(host: u32, pid: pid_t, task: *mut task_t) -> u32;
- pub fn mach_task_self() -> u32;
- pub fn mach_host_self() -> u32;
- //pub fn task_info(host_info: u32, t: u32, c: *mut c_void, x: *mut u32) -> u32;
- pub fn host_statistics64(host_info: u32, x: u32, y: *mut c_void, z: *const u32) -> u32;
- pub fn host_processor_info(host_info: u32, t: u32, num_cpu_u: *mut u32,
- cpu_info: *mut *mut i32, num_cpu_info: *mut u32) -> u32;
- //pub fn host_statistics(host_priv: u32, flavor: u32, host_info: *mut c_void,
- // host_count: *const u32) -> u32;
- pub fn vm_deallocate(target_task: u32, address: *mut i32, size: u32) -> u32;
-}
-
-// TODO: waiting for https://github.com/rust-lang/libc/pull/678
-macro_rules! cfg_if {
- ($(
- if #[cfg($($meta:meta),*)] { $($it:item)* }
- ) else * else {
- $($it2:item)*
- }) => {
- __cfg_if_items! {
- () ;
- $( ( ($($meta),*) ($($it)*) ), )*
- ( () ($($it2)*) ),
- }
- }
-}
-
-// TODO: waiting for https://github.com/rust-lang/libc/pull/678
-macro_rules! __cfg_if_items {
- (($($not:meta,)*) ; ) => {};
- (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
- __cfg_if_apply! { cfg(all(not(any($($not),*)), $($m,)*)), $($it)* }
- __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
- }
-}
-
-// TODO: waiting for https://github.com/rust-lang/libc/pull/678
-macro_rules! __cfg_if_apply {
- ($m:meta, $($it:item)*) => {
- $(#[$m] $it)*
- }
-}
-
-// TODO: waiting for https://github.com/rust-lang/libc/pull/678
-cfg_if! {
- if #[cfg(any(target_arch = "arm", target_arch = "x86"))] {
- pub type timeval32 = ::libc::timeval;
- } else {
- use libc::timeval32;
+// TO BE REMOVED ONCE https://github.com/retep998/winapi-rs/pull/802 IS MERGED!!!
+
+#![allow(non_camel_case_types)]
+#![allow(non_snake_case)]
+#![allow(non_upper_case_globals)]
+#![allow(dead_code)]
+
+use winapi::shared::basetsd::ULONG64;
+use winapi::shared::guiddef::GUID;
+use winapi::shared::ifdef::{NET_IFINDEX, NET_LUID};
+use winapi::shared::minwindef::BYTE;
+use winapi::shared::netioapi::NETIOAPI_API;
+use winapi::shared::ntdef::{PVOID, UCHAR, ULONG, WCHAR};
+use winapi::{ENUM, STRUCT};
+
+const ANY_SIZE: usize = 1;
+
+pub const IF_MAX_STRING_SIZE: usize = 256;
+pub const IF_MAX_PHYS_ADDRESS_LENGTH: usize = 32;
+
+pub type NET_IF_NETWORK_GUID = GUID;
+pub type PMIB_IF_TABLE2 = *mut MIB_IF_TABLE2;
+pub type PMIB_IF_ROW2 = *mut MIB_IF_ROW2;
+
+macro_rules! BITFIELD {
+ ($base:ident $field:ident: $fieldtype:ty [
+ $($thing:ident $set_thing:ident[$r:expr],)+
+ ]) => {
+ impl $base {$(
+ #[inline]
+ pub fn $thing(&self) -> $fieldtype {
+ let size = ::std::mem::size_of::<$fieldtype>() * 8;
+ self.$field << (size - $r.end) >> (size - $r.end + $r.start)
+ }
+ #[inline]
+ pub fn $set_thing(&mut self, val: $fieldtype) {
+ let mask = ((1 << ($r.end - $r.start)) - 1) << $r.start;
+ self.$field &= !mask;
+ self.$field |= (val << $r.start) & mask;
+ }
+ )+}
}
}
-// TODO: waiting for https://github.com/rust-lang/libc/pull/678
-#[repr(C)]
-pub struct if_data64 {
- pub ifi_type: c_uchar,
- pub ifi_typelen: c_uchar,
- pub ifi_physical: c_uchar,
- pub ifi_addrlen: c_uchar,
- pub ifi_hdrlen: c_uchar,
- pub ifi_recvquota: c_uchar,
- pub ifi_xmitquota: c_uchar,
- pub ifi_unused1: c_uchar,
- pub ifi_mtu: uint32_t,
- pub ifi_metric: uint32_t,
- pub ifi_baudrate: uint64_t,
- pub ifi_ipackets: uint64_t,
- pub ifi_ierrors: uint64_t,
- pub ifi_opackets: uint64_t,
- pub ifi_oerrors: uint64_t,
- pub ifi_collisions: uint64_t,
- pub ifi_ibytes: uint64_t,
- pub ifi_obytes: uint64_t,
- pub ifi_imcasts: uint64_t,
- pub ifi_omcasts: uint64_t,
- pub ifi_iqdrops: uint64_t,
- pub ifi_noproto: uint64_t,
- pub ifi_recvtiming: uint32_t,
- pub ifi_xmittiming: uint32_t,
- pub ifi_lastchange: timeval32,
-}
-
-// TODO: waiting for https://github.com/rust-lang/libc/pull/678
-#[repr(C)]
-pub struct if_msghdr2 {
- pub ifm_msglen: c_ushort,
- pub ifm_version: c_uchar,
- pub ifm_type: c_uchar,
- pub ifm_addrs: c_int,
- pub ifm_flags: c_int,
- pub ifm_index: c_ushort,
- pub ifm_snd_len: c_int,
- pub ifm_snd_maxlen: c_int,
- pub ifm_snd_drops: c_int,
- pub ifm_timer: c_int,
- pub ifm_data: if_data64,
-}
-
-#[repr(C)]
-pub struct __CFAllocator {
- __private: c_void,
+STRUCT! {struct MIB_IF_TABLE2 {
+ NumEntries: ULONG,
+ Table: [MIB_IF_ROW2; ANY_SIZE],
+}}
+
+ENUM! {enum NDIS_MEDIUM {
+ NdisMedium802_3 = 0,
+ NdisMedium802_5 = 1,
+ NdisMediumFddi = 2,
+ NdisMediumWan = 3,
+ NdisMediumLocalTalk = 4,
+ NdisMediumDix = 5, // defined for convenience, not a real medium
+ NdisMediumArcnetRaw = 6,
+ NdisMediumArcnet878_2 = 7,
+ NdisMediumAtm = 8,
+ NdisMediumWirelessWan = 9,
+ NdisMediumIrda = 10,
+ NdisMediumBpc = 11,
+ NdisMediumCoWan = 12,
+ NdisMedium1394 = 13,
+ NdisMediumInfiniBand = 14,
+ NdisMediumTunnel = 15,
+ NdisMediumNative802_11 = 16,
+ NdisMediumLoopback = 17,
+ NdisMediumWiMAX = 18,
+ NdisMediumIP = 19,
+ NdisMediumMax = 20, // Not a real medium, defined as an upper-bound
+}}
+
+ENUM! {enum TUNNEL_TYPE {
+ TUNNEL_TYPE_NONE = 0,
+ TUNNEL_TYPE_OTHER = 1,
+ TUNNEL_TYPE_DIRECT = 2,
+ TUNNEL_TYPE_6TO4 = 11,
+ TUNNEL_TYPE_ISATAP = 13,
+ TUNNEL_TYPE_TEREDO = 14,
+ TUNNEL_TYPE_IPHTTPS = 15,
+}}
+
+ENUM! {enum NDIS_PHYSICAL_MEDIUM {
+ NdisPhysicalMediumUnspecified = 0,
+ NdisPhysicalMediumWirelessLan = 1,
+ NdisPhysicalMediumCableModem = 2,
+ NdisPhysicalMediumPhoneLine = 3,
+ NdisPhysicalMediumPowerLine = 4,
+ NdisPhysicalMediumDSL = 5, // includes ADSL and UADSL (G.Lite)
+ NdisPhysicalMediumFibreChannel = 6,
+ NdisPhysicalMedium1394 = 7,
+ NdisPhysicalMediumWirelessWan = 8,
+ NdisPhysicalMediumNative802_11 = 9,
+ NdisPhysicalMediumBluetooth = 10,
+ NdisPhysicalMediumInfiniband = 11,
+ NdisPhysicalMediumWiMax = 12,
+ NdisPhysicalMediumUWB = 13,
+ NdisPhysicalMedium802_3 = 14,
+ NdisPhysicalMedium802_5 = 15,
+ NdisPhysicalMediumIrda = 16,
+ NdisPhysicalMediumWiredWAN = 17,
+ NdisPhysicalMediumWiredCoWan = 18,
+ NdisPhysicalMediumOther = 19,
+ NdisPhysicalMediumMax = 20, // Not a real physical type, defined as an upper-bound
+}}
+
+ENUM! {enum NET_IF_ACCESS_TYPE {
+ NET_IF_ACCESS_LOOPBACK = 1,
+ NET_IF_ACCESS_BROADCAST = 2,
+ NET_IF_ACCESS_POINT_TO_POINT = 3,
+ NET_IF_ACCESS_POINT_TO_MULTI_POINT = 4,
+ NET_IF_ACCESS_MAXIMUM = 5,
+}}
+
+ENUM! {enum NET_IF_DIRECTION_TYPE {
+ NET_IF_DIRECTION_SENDRECEIVE = 0,
+ NET_IF_DIRECTION_SENDONLY = 1,
+ NET_IF_DIRECTION_RECEIVEONLY = 2,
+ NET_IF_DIRECTION_MAXIMUM = 3,
+}}
+
+ENUM! {enum IF_OPER_STATUS {
+ IfOperStatusUp = 1,
+ IfOperStatusDown = 2,
+ IfOperStatusTesting = 3,
+ IfOperStatusUnknown = 4,
+ IfOperStatusDormant = 5,
+ IfOperStatusNotPresent = 6,
+ IfOperStatusLowerLayerDown = 7,
+}}
+
+ENUM! {enum NET_IF_ADMIN_STATUS {
+ NET_IF_ADMIN_STATUS_UP = 1,
+ NET_IF_ADMIN_STATUS_DOWN = 2,
+ NET_IF_ADMIN_STATUS_TESTING = 3,
+}}
+
+ENUM! {enum NET_IF_MEDIA_CONNECT_STATE {
+ MediaConnectStateUnknown = 0,
+ MediaConnectStateConnected = 1,
+ MediaConnectStateDisconnected = 2,
+}}
+
+ENUM! {enum NET_IF_CONNECTION_TYPE {
+ NET_IF_CONNECTION_DEDICATED = 1,
+ NET_IF_CONNECTION_PASSIVE = 2,
+ NET_IF_CONNECTION_DEMAND = 3,
+ NET_IF_CONNECTION_MAXIMUM = 4,
+}}
+
+STRUCT! {struct MIB_IF_ROW2_InterfaceAndOperStatusFlags {
+ bitfield: BYTE,
+}}
+BITFIELD! {MIB_IF_ROW2_InterfaceAndOperStatusFlags bitfield: BYTE [
+ HardwareInterface set_HardwareInterface[0..1],
+ FilterInterface set_FilterInterface[1..2],
+ ConnectorPresent set_ConnectorPresent[2..3],
+ NotAuthenticated set_NotAuthenticated[3..4],
+ NotMediaConnected set_NotMediaConnected[4..5],
+ Paused set_Paused[5..6],
+ LowPower set_LowPower[6..7],
+ EndPointInterface set_EndPointInterface[7..8],
+]}
+
+STRUCT! {struct MIB_IF_ROW2 {
+ InterfaceLuid: NET_LUID,
+ InterfaceIndex: NET_IFINDEX,
+ InterfaceGuid: GUID,
+ Alias: [WCHAR; IF_MAX_STRING_SIZE + 1],
+ Description: [WCHAR; IF_MAX_STRING_SIZE + 1],
+ PhysicalAddressLength: ULONG,
+ PhysicalAddress: [UCHAR; IF_MAX_PHYS_ADDRESS_LENGTH],
+ PermanentPhysicalAddress: [UCHAR; IF_MAX_PHYS_ADDRESS_LENGTH],
+ Mtu: ULONG,
+ Type: ULONG, // Interface Type.
+ TunnelType: TUNNEL_TYPE, // Tunnel Type, if Type = IF_TUNNEL.
+ MediaType: NDIS_MEDIUM,
+ PhysicalMediumType: NDIS_PHYSICAL_MEDIUM,
+ AccessType: NET_IF_ACCESS_TYPE,
+ DirectionType: NET_IF_DIRECTION_TYPE,
+ InterfaceAndOperStatusFlags: MIB_IF_ROW2_InterfaceAndOperStatusFlags,
+ OperStatus: IF_OPER_STATUS,
+ AdminStatus: NET_IF_ADMIN_STATUS,
+ MediaConnectState: NET_IF_MEDIA_CONNECT_STATE,
+ NetworkGuid: NET_IF_NETWORK_GUID,
+ ConnectionType: NET_IF_CONNECTION_TYPE,
+ TransmitLinkSpeed: ULONG64,
+ ReceiveLinkSpeed: ULONG64,
+ InOctets: ULONG64,
+ InUcastPkts: ULONG64,
+ InNUcastPkts: ULONG64,
+ InDiscards: ULONG64,
+ InErrors: ULONG64,
+ InUnknownProtos: ULONG64,
+ InUcastOctets: ULONG64,
+ InMulticastOctets: ULONG64,
+ InBroadcastOctets: ULONG64,
+ OutOctets: ULONG64,
+ OutUcastPkts: ULONG64,
+ OutNUcastPkts: ULONG64,
+ OutDiscards: ULONG64,
+ OutErrors: ULONG64,
+ OutUcastOctets: ULONG64,
+ OutMulticastOctets: ULONG64,
+ OutBroadcastOctets: ULONG64,
+ OutQLen: ULONG64,
+}}
+
+extern "system" {
+ pub fn GetIfTable2(Table: *mut PMIB_IF_TABLE2) -> NETIOAPI_API;
+ pub fn GetIfEntry2(Row: PMIB_IF_ROW2) -> NETIOAPI_API;
+ pub fn FreeMibTable(Memory: PVOID);
}
-
-#[repr(C)]
-pub struct __CFDictionary {
- __private: c_void,
-}
-
-#[repr(C)]
-pub struct __CFString {
- __private: c_void,
-}
-
-pub type CFAllocatorRef = *const __CFAllocator;
-pub type CFMutableDictionaryRef = *mut __CFDictionary;
-pub type CFDictionaryRef = *const __CFDictionary;
-#[allow(non_camel_case_types)]
-pub type io_name_t = [u8; 128];
-#[allow(non_camel_case_types)]
-pub type io_registry_entry_t = io_object_t;
-pub type CFTypeRef = *const c_void;
-pub type CFStringRef = *const __CFString;
-
-//#[allow(non_camel_case_types)]
-//pub type policy_t = i32;
-#[allow(non_camel_case_types)]
-//pub type integer_t = i32;
-//#[allow(non_camel_case_types)]
-//pub type time_t = i64;
-//#[allow(non_camel_case_types)]
-//pub type suseconds_t = i32;
-//#[allow(non_camel_case_types)]
-//pub type mach_vm_size_t = u64;
-//#[allow(non_camel_case_types)]
-//pub type task_t = u32;
-//#[allow(non_camel_case_types)]
-//pub type pid_t = i32;
-#[allow(non_camel_case_types)]
-pub type natural_t = u32;
-#[allow(non_camel_case_types)]
-pub type mach_port_t = u32;
-#[allow(non_camel_case_types)]
-pub type io_object_t = mach_port_t;
-#[allow(non_camel_case_types)]
-pub type io_iterator_t = io_object_t;
-#[allow(non_camel_case_types)]
-pub type io_connect_t = io_object_t;
-#[allow(non_camel_case_types)]
-pub type boolean_t = c_uint;
-#[allow(non_camel_case_types)]
-pub type kern_return_t = c_int;
-pub type Boolean = c_uchar;
-pub type IOOptionBits = u32;
-pub type CFStringEncoding = u32;
-
-/*#[repr(C)]
-pub struct task_thread_times_info {
- pub user_time: time_value,
- pub system_time: time_value,
-}*/
-
-/*#[repr(C)]
-pub struct task_basic_info_64 {
- pub suspend_count: integer_t,
- pub virtual_size: mach_vm_size_t,
- pub resident_size: mach_vm_size_t,
- pub user_time: time_value_t,
- pub system_time: time_value_t,
- pub policy: policy_t,
-}*/
-
-#[repr(C)]
-pub struct vm_statistics64 {
- pub free_count: natural_t,
- pub active_count: natural_t,
- pub inactive_count: natural_t,
- pub wire_count: natural_t,
- pub zero_fill_count: u64,
- pub reactivations: u64,
- pub pageins: u64,
- pub pageouts: u64,
- pub faults: u64,
- pub cow_faults: u64,
- pub lookups: u64,
- pub hits: u64,
- pub purges: u64,
- pub purgeable_count: natural_t,
- pub speculative_count: natural_t,
- pub decompressions: u64,
- pub compressions: u64,
- pub swapins: u64,
- pub swapouts: u64,
- pub compressor_page_count: natural_t,
- pub throttled_count: natural_t,
- pub external_page_count: natural_t,
- pub internal_page_count: natural_t,
- pub total_uncompressed_pages_in_compressor: u64,
-}
-
-#[repr(C)]
-pub struct Val_t {
- pub key: [i8; 5],
- pub data_size: u32,
- pub data_type: [i8; 5], // UInt32Char_t
- pub bytes: [i8; 32], // SMCBytes_t
-}
-
-#[repr(C)]
-pub struct KeyData_vers_t {
- pub major: u8,
- pub minor: u8,
- pub build: u8,
- pub reserved: [u8; 1],
- pub release: u16,
-}
-
-#[repr(C)]
-pub struct KeyData_pLimitData_t {
- pub version: u16,
- pub length: u16,
- pub cpu_plimit: u32,
- pub gpu_plimit: u32,
- pub mem_plimit: u32,
-}
-
-#[repr(C)]
-pub struct KeyData_keyInfo_t {
- pub data_size: u32,
- pub data_type: u32,
- pub data_attributes: u8,
-}
-
-#[repr(C)]
-pub struct KeyData_t {
- pub key: u32,
- pub vers: KeyData_vers_t,
- pub p_limit_data: KeyData_pLimitData_t,
- pub key_info: KeyData_keyInfo_t,
- pub result: u8,
- pub status: u8,
- pub data8: u8,
- pub data32: u32,
- pub bytes: [i8; 32], // SMCBytes_t
-}
-
-#[repr(C)]
-pub struct xsw_usage {
- pub xsu_total: u64,
- pub xsu_avail: u64,
- pub xsu_used: u64,
- pub xsu_pagesize: u32,
- pub xsu_encrypted: boolean_t,
-}
-
-//pub const HOST_CPU_LOAD_INFO_COUNT: usize = 4;
-//pub const HOST_CPU_LOAD_INFO: u32 = 3;
-pub const KERN_SUCCESS: u32 = 0;
-
-pub const HW_NCPU: u32 = 3;
-pub const CTL_HW: u32 = 6;
-pub const CTL_VM: u32 = 2;
-pub const VM_SWAPUSAGE: u32 = 5;
-pub const PROCESSOR_CPU_LOAD_INFO: u32 = 2;
-pub const CPU_STATE_USER: u32 = 0;
-pub const CPU_STATE_SYSTEM: u32 = 1;
-pub const CPU_STATE_IDLE: u32 = 2;
-pub const CPU_STATE_NICE: u32 = 3;
-pub const CPU_STATE_MAX: usize = 4;
-pub const HW_MEMSIZE: u32 = 24;
-
-//pub const TASK_THREAD_TIMES_INFO: u32 = 3;
-//pub const TASK_THREAD_TIMES_INFO_COUNT: u32 = 4;
-//pub const TASK_BASIC_INFO_64: u32 = 5;
-//pub const TASK_BASIC_INFO_64_COUNT: u32 = 10;
-pub const HOST_VM_INFO64: u32 = 4;
-pub const HOST_VM_INFO64_COUNT: u32 = 38;
-
-pub const MACH_PORT_NULL: i32 = 0;
-pub const KERNEL_INDEX_SMC: i32 = 2;
-pub const SMC_CMD_READ_KEYINFO: u8 = 9;
-pub const SMC_CMD_READ_BYTES: u8 = 5;
-
-pub const KIO_RETURN_SUCCESS: i32 = 0;
-#[allow(non_upper_case_globals)]
-pub const kCFStringEncodingMacRoman: CFStringEncoding = 0;
diff --git a/src/windows/mod.rs b/src/windows/mod.rs
--- a/src/windows/mod.rs
+++ b/src/windows/mod.rs
@@ -4,24 +4,8 @@
// Copyright (c) 2015 Guillaume Gomez
//
-/*pub mod component;
-pub mod disk;
-mod ffi;
-pub mod network;
-pub mod process;
-pub mod processor;
-pub mod system;
-
-pub use self::component::Component;
-pub use self::disk::{Disk, DiskType};
-pub use self::network::NetworkData;
-pub use self::process::{Process,ProcessStatus};
-pub use self::processor::Processor;
-pub use self::system::System;*/
-
mod component;
mod disk;
-//mod ffi;
#[macro_use]
mod macros;
mod network;
diff --git a/src/windows/mod.rs b/src/windows/mod.rs
--- a/src/windows/mod.rs
+++ b/src/windows/mod.rs
@@ -30,9 +14,11 @@ mod processor;
mod system;
mod tools;
+mod ffi;
+
pub use self::component::Component;
pub use self::disk::{Disk, DiskType};
-pub use self::network::NetworkData;
+pub use self::network::{NetworkData, Networks};
pub use self::process::{Process, ProcessStatus};
pub use self::processor::Processor;
pub use self::system::System;
diff --git a/src/windows/network.rs b/src/windows/network.rs
--- a/src/windows/network.rs
+++ b/src/windows/network.rs
@@ -4,54 +4,168 @@
// Copyright (c) 2017 Guillaume Gomez
//
-use windows::processor::Query;
-use windows::tools::KeyHandler;
+use std::collections::{HashMap, HashSet};
+
+use windows::ffi::{self, MIB_IF_ROW2, PMIB_IF_TABLE2};
use NetworkExt;
+use NetworksExt;
+use NetworksIter;
+
+use winapi::shared::ifdef::NET_LUID;
+use winapi::shared::winerror::NO_ERROR;
+
+macro_rules! old_and_new {
+ ($ty_:expr, $name:ident, $old:ident, $new_val:expr) => {{
+ $ty_.$old = $ty_.$name;
+ $ty_.$name = $new_val;
+ }};
+}
+
+/// Network interfaces.
+///
+/// ```no_run
+/// use sysinfo::{NetworksExt, System, SystemExt};
+///
+/// let s = System::new_all();
+/// let networks = s.get_networks();
+/// ```
+pub struct Networks {
+ interfaces: HashMap<String, NetworkData>,
+}
+
+impl Networks {
+ pub(crate) fn new() -> Networks {
+ Networks {
+ interfaces: HashMap::new(),
+ }
+ }
+}
+
+impl NetworksExt for Networks {
+ fn iter<'a>(&'a self) -> NetworksIter<'a> {
+ NetworksIter::new(self.interfaces.iter())
+ }
+
+ fn refresh_networks_list(&mut self) {
+ let mut table: PMIB_IF_TABLE2 = ::std::ptr::null_mut();
+ if unsafe { ffi::GetIfTable2(&mut table) } != NO_ERROR {
+ return;
+ }
+ let mut to_be_removed = HashSet::with_capacity(self.interfaces.len());
+
+ for key in self.interfaces.keys() {
+ to_be_removed.insert(key.clone());
+ }
+ // In here, this is tricky: we have to filter out the software interfaces to only keep
+ // the hardware ones. To do so, we first check the connection potential speed (if 0, not
+ // interesting), then we check its state: if not open, not interesting either. And finally,
+ // we count the members of a same group: if there is more than 1, then it's software level.
+ let mut groups = HashMap::new();
+ let mut indexes = Vec::new();
+ let ptr = unsafe { (*table).Table.as_ptr() };
+ for i in 0..unsafe { *table }.NumEntries {
+ let ptr = unsafe { &*ptr.offset(i as _) };
+ if ptr.TransmitLinkSpeed == 0 && ptr.ReceiveLinkSpeed == 0 {
+ continue;
+ } else if ptr.MediaConnectState == ffi::MediaConnectStateDisconnected
+ || ptr.PhysicalAddressLength == 0
+ {
+ continue;
+ }
+ let id = vec![
+ ptr.InterfaceGuid.Data2,
+ ptr.InterfaceGuid.Data3,
+ ptr.InterfaceGuid.Data4[0] as _,
+ ptr.InterfaceGuid.Data4[1] as _,
+ ptr.InterfaceGuid.Data4[2] as _,
+ ptr.InterfaceGuid.Data4[3] as _,
+ ptr.InterfaceGuid.Data4[4] as _,
+ ptr.InterfaceGuid.Data4[5] as _,
+ ptr.InterfaceGuid.Data4[6] as _,
+ ptr.InterfaceGuid.Data4[7] as _,
+ ];
+ let entry = groups.entry(id.clone()).or_insert(0);
+ *entry += 1;
+ if *entry > 1 {
+ continue;
+ }
+ indexes.push((i, id));
+ }
+ for (i, id) in indexes {
+ let ptr = unsafe { &*ptr.offset(i as _) };
+ if *groups.get(&id).unwrap_or(&0) > 1 {
+ continue;
+ }
+ let mut pos = 0;
+ for x in ptr.Alias.iter() {
+ if *x == 0 {
+ break;
+ }
+ pos += 1;
+ }
+ let interface_name = match String::from_utf16(&ptr.Alias[..pos]) {
+ Ok(s) => s,
+ _ => continue,
+ };
+ to_be_removed.remove(&interface_name);
+ let mut interface =
+ self.interfaces
+ .entry(interface_name)
+ .or_insert_with(|| NetworkData {
+ id: ptr.InterfaceLuid,
+ current_out: ptr.OutOctets,
+ old_out: ptr.OutOctets,
+ current_in: ptr.InOctets,
+ old_in: ptr.InOctets,
+ });
+ old_and_new!(interface, current_out, old_out, ptr.OutOctets);
+ old_and_new!(interface, current_in, old_in, ptr.InOctets);
+ }
+ unsafe {
+ ffi::FreeMibTable(table as _);
+ }
+ for key in to_be_removed {
+ self.interfaces.remove(&key);
+ }
+ }
+
+ fn refresh(&mut self) {
+ let mut entry: MIB_IF_ROW2 = unsafe { ::std::mem::MaybeUninit::uninit().assume_init() };
+ for (_, interface) in self.interfaces.iter_mut() {
+ entry.InterfaceLuid = interface.id;
+ entry.InterfaceIndex = 0; // to prevent the function to pick this one as index
+ if unsafe { ffi::GetIfEntry2(&mut entry) } != NO_ERROR {
+ continue;
+ }
+ old_and_new!(interface, current_out, old_out, entry.OutOctets);
+ old_and_new!(interface, current_in, old_in, entry.InOctets);
+ }
+ }
+}
/// Contains network information.
pub struct NetworkData {
+ id: NET_LUID,
current_out: u64,
+ old_out: u64,
current_in: u64,
- keys_in: Vec<KeyHandler>,
- keys_out: Vec<KeyHandler>,
+ old_in: u64,
}
impl NetworkExt for NetworkData {
fn get_income(&self) -> u64 {
- self.current_in
+ self.current_in - self.old_in
}
fn get_outcome(&self) -> u64 {
- self.current_out
+ self.current_out - self.old_out
}
-}
-pub fn new() -> NetworkData {
- NetworkData {
- current_in: 0,
- current_out: 0,
- keys_in: Vec::new(),
- keys_out: Vec::new(),
+ fn get_total_income(&self) -> u64 {
+ self.current_in
}
-}
-pub fn refresh(network: &mut NetworkData, query: &Option<Query>) {
- if let &Some(ref query) = query {
- network.current_in = 0;
- for key in &network.keys_in {
- network.current_in += query.get_u64(&key.unique_id).expect("key disappeared");
- }
- network.current_out = 0;
- for key in &network.keys_out {
- network.current_out += query.get_u64(&key.unique_id).expect("key disappeared");
- }
+ fn get_total_outcome(&self) -> u64 {
+ self.current_out
}
}
-
-pub fn get_keys_in(network: &mut NetworkData) -> &mut Vec<KeyHandler> {
- &mut network.keys_in
-}
-
-pub fn get_keys_out(network: &mut NetworkData) -> &mut Vec<KeyHandler> {
- &mut network.keys_out
-}
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -5,24 +5,120 @@
//
use std::collections::HashMap;
+use std::mem;
+use std::ops::DerefMut;
+use std::ptr::null_mut;
use std::sync::{Arc, Mutex};
-use std::thread::{self /*, sleep*/, JoinHandle};
-//use std::time::Duration;
use windows::tools::KeyHandler;
+use LoadAvg;
use ProcessorExt;
-use winapi::shared::minwindef::{FALSE, ULONG};
+use ntapi::ntpoapi::PROCESSOR_POWER_INFORMATION;
+
+use winapi::shared::minwindef::FALSE;
use winapi::shared::winerror::ERROR_SUCCESS;
use winapi::um::handleapi::CloseHandle;
use winapi::um::pdh::{
- PdhAddCounterW, PdhCloseQuery, PdhCollectQueryData, PdhCollectQueryDataEx,
+ PdhAddCounterW, PdhAddEnglishCounterA, PdhCloseQuery, PdhCollectQueryDataEx,
PdhGetFormattedCounterValue, PdhOpenQueryA, PdhRemoveCounter, PDH_FMT_COUNTERVALUE,
- PDH_FMT_DOUBLE, PDH_FMT_LARGE, PDH_HCOUNTER, PDH_HQUERY,
+ PDH_FMT_DOUBLE, PDH_HCOUNTER, PDH_HQUERY,
};
-use winapi::um::synchapi::{CreateEventA, WaitForSingleObject};
-use winapi::um::winbase::{INFINITE, WAIT_OBJECT_0};
-use winapi::um::winnt::HANDLE;
+use winapi::um::powerbase::CallNtPowerInformation;
+use winapi::um::synchapi::CreateEventA;
+use winapi::um::sysinfoapi::SYSTEM_INFO;
+use winapi::um::winbase::{RegisterWaitForSingleObject, INFINITE};
+use winapi::um::winnt::{ProcessorInformation, BOOLEAN, HANDLE, PVOID, WT_EXECUTEDEFAULT};
+
+// This formula comes from linux's include/linux/sched/loadavg.h
+// https://github.com/torvalds/linux/blob/345671ea0f9258f410eb057b9ced9cefbbe5dc78/include/linux/sched/loadavg.h#L20-L23
+const LOADAVG_FACTOR_1F: f64 = 0.9200444146293232478931553241;
+const LOADAVG_FACTOR_5F: f64 = 0.6592406302004437462547604110;
+const LOADAVG_FACTOR_15F: f64 = 0.2865047968601901003248854266;
+// The time interval in seconds between taking load counts, same as Linux
+const SAMPLING_INTERVAL: usize = 5;
+
+// maybe use a read/write lock instead?
+static LOAD_AVG: once_cell::sync::Lazy<Mutex<Option<LoadAvg>>> =
+ once_cell::sync::Lazy::new(|| unsafe { init_load_avg() });
+
+pub(crate) fn get_load_average() -> LoadAvg {
+ if let Ok(avg) = LOAD_AVG.lock() {
+ if let Some(avg) = &*avg {
+ return avg.clone();
+ }
+ }
+ return LoadAvg::default();
+}
+
+unsafe extern "system" fn load_avg_callback(counter: PVOID, _: BOOLEAN) {
+ let mut display_value: PDH_FMT_COUNTERVALUE = mem::MaybeUninit::uninit().assume_init();
+
+ if PdhGetFormattedCounterValue(counter as _, PDH_FMT_DOUBLE, null_mut(), &mut display_value)
+ != ERROR_SUCCESS as _
+ {
+ return;
+ }
+ if let Ok(mut avg) = LOAD_AVG.lock() {
+ if let Some(avg) = avg.deref_mut() {
+ let current_load = display_value.u.doubleValue();
+
+ avg.one = avg.one * LOADAVG_FACTOR_1F + current_load * (1.0 - LOADAVG_FACTOR_1F);
+ avg.five = avg.five * LOADAVG_FACTOR_5F + current_load * (1.0 - LOADAVG_FACTOR_5F);
+ avg.fifteen =
+ avg.fifteen * LOADAVG_FACTOR_15F + current_load * (1.0 - LOADAVG_FACTOR_15F);
+ }
+ }
+}
+
+unsafe fn init_load_avg() -> Mutex<Option<LoadAvg>> {
+ // You can see the original implementation here: https://github.com/giampaolo/psutil
+ let mut query = null_mut();
+
+ if PdhOpenQueryA(null_mut(), 0, &mut query) != ERROR_SUCCESS as _ {
+ return Mutex::new(None);
+ }
+
+ let mut counter: PDH_HCOUNTER = mem::zeroed();
+ if PdhAddEnglishCounterA(
+ query,
+ b"\\System\\Processor Queue Length\0".as_ptr() as _,
+ 0,
+ &mut counter,
+ ) != ERROR_SUCCESS as _
+ {
+ PdhCloseQuery(query);
+ return Mutex::new(None);
+ }
+
+ let event = CreateEventA(null_mut(), FALSE, FALSE, b"LoadUpdateEvent\0".as_ptr() as _);
+ if event.is_null() {
+ PdhCloseQuery(query);
+ return Mutex::new(None);
+ }
+
+ if PdhCollectQueryDataEx(query, SAMPLING_INTERVAL as _, event) != ERROR_SUCCESS as _ {
+ PdhCloseQuery(query);
+ return Mutex::new(None);
+ }
+
+ let mut wait_handle = null_mut();
+ if RegisterWaitForSingleObject(
+ &mut wait_handle,
+ event,
+ Some(load_avg_callback),
+ counter as _,
+ INFINITE,
+ WT_EXECUTEDEFAULT,
+ ) == 0
+ {
+ PdhRemoveCounter(counter);
+ PdhCloseQuery(query);
+ return Mutex::new(None);
+ }
+
+ return Mutex::new(Some(LoadAvg::default()));
+}
#[derive(Debug)]
pub enum CounterValue {
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -37,13 +133,6 @@ impl CounterValue {
_ => panic!("not a float"),
}
}
-
- pub fn get_u64(&self) -> u64 {
- match *self {
- CounterValue::Integer(v) => v,
- _ => panic!("not an integer"),
- }
- }
}
#[allow(dead_code)]
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -81,56 +170,6 @@ struct InternalQuery {
unsafe impl Send for InternalQuery {}
unsafe impl Sync for InternalQuery {}
-impl InternalQuery {
- pub fn record(&self) -> bool {
- unsafe {
- let status = PdhCollectQueryData(self.query);
- if status != ERROR_SUCCESS as i32 {
- eprintln!("PdhCollectQueryData error: {:x} {:?}", status, self.query);
- return false;
- }
- if PdhCollectQueryDataEx(self.query, 1, self.event) != ERROR_SUCCESS as i32 {
- return false;
- }
- if WaitForSingleObject(self.event, INFINITE) == WAIT_OBJECT_0 {
- if let Ok(ref mut data) = self.data.lock() {
- let mut counter_type: ULONG = 0;
- let mut display_value: PDH_FMT_COUNTERVALUE = ::std::mem::zeroed();
- for (_, x) in data.iter_mut() {
- match x.value {
- CounterValue::Float(ref mut value) => {
- if PdhGetFormattedCounterValue(
- x.counter,
- PDH_FMT_DOUBLE,
- &mut counter_type,
- &mut display_value,
- ) == ERROR_SUCCESS as i32
- {
- *value = *display_value.u.doubleValue() as f32 / 100f32;
- }
- }
- CounterValue::Integer(ref mut value) => {
- if PdhGetFormattedCounterValue(
- x.counter,
- PDH_FMT_LARGE,
- &mut counter_type,
- &mut display_value,
- ) == ERROR_SUCCESS as i32
- {
- *value = *display_value.u.largeValue() as u64;
- }
- }
- }
- }
- }
- true
- } else {
- false
- }
- }
- }
-}
-
impl Drop for InternalQuery {
fn drop(&mut self) {
unsafe {
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -153,20 +192,15 @@ impl Drop for InternalQuery {
pub struct Query {
internal: Arc<InternalQuery>,
- thread: Option<JoinHandle<()>>,
}
impl Query {
pub fn new() -> Option<Query> {
- let mut query = ::std::ptr::null_mut();
+ let mut query = null_mut();
unsafe {
- if PdhOpenQueryA(::std::ptr::null_mut(), 0, &mut query) == ERROR_SUCCESS as i32 {
- let event = CreateEventA(
- ::std::ptr::null_mut(),
- FALSE,
- FALSE,
- b"some_ev\0".as_ptr() as *const i8,
- );
+ if PdhOpenQueryA(null_mut(), 0, &mut query) == ERROR_SUCCESS as i32 {
+ let event =
+ CreateEventA(null_mut(), FALSE, FALSE, b"some_ev\0".as_ptr() as *const i8);
if event.is_null() {
PdhCloseQuery(query);
None
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -176,10 +210,7 @@ impl Query {
event: event,
data: Mutex::new(HashMap::new()),
});
- Some(Query {
- internal: q,
- thread: None,
- })
+ Some(Query { internal: q })
}
} else {
None
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -196,15 +227,6 @@ impl Query {
None
}
- pub fn get_u64(&self, name: &String) -> Option<u64> {
- if let Ok(data) = self.internal.data.lock() {
- if let Some(ref counter) = data.get(name) {
- return Some(counter.value.get_u64());
- }
- }
- None
- }
-
pub fn add_counter(&mut self, name: &String, getter: Vec<u16>, value: CounterValue) -> bool {
if let Ok(data) = self.internal.data.lock() {
if data.contains_key(name) {
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -233,13 +255,6 @@ impl Query {
}
true
}
-
- pub fn start(&mut self) {
- let internal = Arc::clone(&self.internal);
- self.thread = Some(thread::spawn(move || loop {
- internal.record();
- }));
- }
}
/// Struct containing a processor information.
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -248,6 +263,9 @@ pub struct Processor {
cpu_usage: f32,
key_idle: Option<KeyHandler>,
key_used: Option<KeyHandler>,
+ vendor_id: String,
+ brand: String,
+ frequency: u64,
}
impl ProcessorExt for Processor {
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -258,25 +276,139 @@ impl ProcessorExt for Processor {
fn get_name(&self) -> &str {
&self.name
}
+
+ fn get_frequency(&self) -> u64 {
+ self.frequency
+ }
+
+ fn get_vendor_id(&self) -> &str {
+ &self.vendor_id
+ }
+
+ fn get_brand(&self) -> &str {
+ &self.brand
+ }
}
impl Processor {
- fn new_with_values(name: &str) -> Processor {
+ pub(crate) fn new_with_values(
+ name: &str,
+ vendor_id: String,
+ brand: String,
+ frequency: u64,
+ ) -> Processor {
Processor {
name: name.to_owned(),
cpu_usage: 0f32,
key_idle: None,
key_used: None,
+ vendor_id,
+ brand,
+ frequency,
}
}
+
+ pub(crate) fn set_cpu_usage(&mut self, value: f32) {
+ self.cpu_usage = value;
+ }
}
-pub fn create_processor(name: &str) -> Processor {
- Processor::new_with_values(name)
+fn get_vendor_id_not_great(info: &SYSTEM_INFO) -> String {
+ use winapi::um::winnt;
+ // https://docs.microsoft.com/fr-fr/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info
+ match unsafe { info.u.s() }.wProcessorArchitecture {
+ winnt::PROCESSOR_ARCHITECTURE_INTEL => "Intel x86",
+ winnt::PROCESSOR_ARCHITECTURE_MIPS => "MIPS",
+ winnt::PROCESSOR_ARCHITECTURE_ALPHA => "RISC Alpha",
+ winnt::PROCESSOR_ARCHITECTURE_PPC => "PPC",
+ winnt::PROCESSOR_ARCHITECTURE_SHX => "SHX",
+ winnt::PROCESSOR_ARCHITECTURE_ARM => "ARM",
+ winnt::PROCESSOR_ARCHITECTURE_IA64 => "Intel Itanium-based x64",
+ winnt::PROCESSOR_ARCHITECTURE_ALPHA64 => "RISC Alpha x64",
+ winnt::PROCESSOR_ARCHITECTURE_MSIL => "MSIL",
+ winnt::PROCESSOR_ARCHITECTURE_AMD64 => "(Intel or AMD) x64",
+ winnt::PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 => "Intel Itanium-based x86",
+ winnt::PROCESSOR_ARCHITECTURE_NEUTRAL => "unknown",
+ winnt::PROCESSOR_ARCHITECTURE_ARM64 => "ARM x64",
+ winnt::PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 => "ARM",
+ winnt::PROCESSOR_ARCHITECTURE_IA32_ON_ARM64 => "Intel Itanium-based x86",
+ _ => "unknown",
+ }
+ .to_owned()
+}
+
+#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) {
+ #[cfg(target_arch = "x86")]
+ use std::arch::x86::__cpuid;
+ #[cfg(target_arch = "x86_64")]
+ use std::arch::x86_64::__cpuid;
+
+ fn add_u32(v: &mut Vec<u8>, i: u32) {
+ let i = &i as *const u32 as *const u8;
+ unsafe {
+ v.push(*i);
+ v.push(*i.offset(1));
+ v.push(*i.offset(2));
+ v.push(*i.offset(3));
+ }
+ }
+
+ // First, we try to get the complete name.
+ let res = unsafe { __cpuid(0x80000000) };
+ let n_ex_ids = res.eax;
+ let brand = if n_ex_ids >= 0x80000004 {
+ let mut extdata = Vec::with_capacity(5);
+
+ for i in 0x80000000..=n_ex_ids {
+ extdata.push(unsafe { __cpuid(i) });
+ }
+
+ let mut out = Vec::with_capacity(4 * 4 * 3); // 4 * u32 * nb_entries
+ for i in 2..5 {
+ add_u32(&mut out, extdata[i].eax);
+ add_u32(&mut out, extdata[i].ebx);
+ add_u32(&mut out, extdata[i].ecx);
+ add_u32(&mut out, extdata[i].edx);
+ }
+ let mut pos = 0;
+ for e in out.iter() {
+ if *e == 0 {
+ break;
+ }
+ pos += 1;
+ }
+ match ::std::str::from_utf8(&out[..pos]) {
+ Ok(s) => s.to_owned(),
+ _ => String::new(),
+ }
+ } else {
+ String::new()
+ };
+
+ // Failed to get full name, let's retry for the short version!
+ let res = unsafe { __cpuid(0) };
+ let mut x = Vec::with_capacity(16); // 3 * u32
+ add_u32(&mut x, res.ebx);
+ add_u32(&mut x, res.edx);
+ add_u32(&mut x, res.ecx);
+ let mut pos = 0;
+ for e in x.iter() {
+ if *e == 0 {
+ break;
+ }
+ pos += 1;
+ }
+ let vendor_id = match ::std::str::from_utf8(&x[..pos]) {
+ Ok(s) => s.to_owned(),
+ Err(_) => get_vendor_id_not_great(info),
+ };
+ (vendor_id, brand)
}
-pub fn set_cpu_usage(p: &mut Processor, value: f32) {
- p.cpu_usage = value;
+#[cfg(all(not(target_arch = "x86_64"), not(target_arch = "x86")))]
+pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) {
+ (get_vendor_id_not_great(info), String::new())
}
pub fn get_key_idle(p: &mut Processor) -> &mut Option<KeyHandler> {
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -286,3 +418,35 @@ pub fn get_key_idle(p: &mut Processor) -> &mut Option<KeyHandler> {
pub fn get_key_used(p: &mut Processor) -> &mut Option<KeyHandler> {
&mut p.key_used
}
+
+// From https://stackoverflow.com/a/43813138:
+//
+// If your PC has 64 or fewer logical processors installed, the above code will work fine. However,
+// if your PC has more than 64 logical processors installed, use GetActiveProcessorCount() or
+// GetLogicalProcessorInformation() to determine the total number of logical processors installed.
+pub fn get_frequencies(nb_processors: usize) -> Vec<u64> {
+ let size = nb_processors * mem::size_of::<PROCESSOR_POWER_INFORMATION>();
+ let mut infos: Vec<PROCESSOR_POWER_INFORMATION> = Vec::with_capacity(nb_processors);
+
+ if unsafe {
+ CallNtPowerInformation(
+ ProcessorInformation,
+ null_mut(),
+ 0,
+ infos.as_mut_ptr() as _,
+ size as _,
+ )
+ } == 0
+ {
+ unsafe {
+ infos.set_len(nb_processors);
+ }
+ // infos.Number
+ infos
+ .into_iter()
+ .map(|i| i.CurrentMhz as u64)
+ .collect::<Vec<_>>()
+ } else {
+ vec![0; nb_processors]
+ }
+}
diff --git a/src/windows/system.rs b/src/windows/system.rs
--- a/src/windows/system.rs
+++ b/src/windows/system.rs
@@ -13,12 +13,13 @@ use std::collections::HashMap;
use std::mem::{size_of, zeroed};
use DiskExt;
+use LoadAvg;
+use Networks;
use Pid;
use ProcessExt;
use RefreshKind;
use SystemExt;
-use windows::network::{self, NetworkData};
use windows::process::{
compute_cpu_usage, get_handle, get_system_computation_time, update_proc_info, Process,
};
diff --git a/src/windows/system.rs b/src/windows/system.rs
--- a/src/windows/system.rs
+++ b/src/windows/system.rs
@@ -28,12 +29,10 @@ use windows::tools::*;
use ntapi::ntexapi::{
NtQuerySystemInformation, SystemProcessInformation, SYSTEM_PROCESS_INFORMATION,
};
-use winapi::shared::minwindef::{DWORD, FALSE};
+use winapi::shared::minwindef::FALSE;
use winapi::shared::ntdef::{PVOID, ULONG};
use winapi::shared::ntstatus::STATUS_INFO_LENGTH_MISMATCH;
-use winapi::shared::winerror::ERROR_SUCCESS;
use winapi::um::minwinbase::STILL_ACTIVE;
-use winapi::um::pdh::PdhEnumObjectItemsW;
use winapi::um::processthreadsapi::GetExitCodeProcess;
use winapi::um::sysinfoapi::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
use winapi::um::winnt::HANDLE;
diff --git a/src/windows/system.rs b/src/windows/system.rs
--- a/src/windows/system.rs
+++ b/src/windows/system.rs
@@ -51,7 +50,7 @@ pub struct System {
temperatures: Vec<Component>,
disks: Vec<Disk>,
query: Option<Query>,
- network: NetworkData,
+ networks: Networks,
uptime: u64,
}
diff --git a/src/windows/system.rs b/src/windows/system.rs
--- a/src/windows/system.rs
+++ b/src/windows/system.rs
@@ -74,7 +73,7 @@ impl SystemExt for System {
temperatures: component::get_components(),
disks: Vec::with_capacity(2),
query: Query::new(),
- network: network::new(),
+ networks: Networks::new(),
uptime: get_uptime(),
};
// TODO: in case a translation fails, it might be nice to log it somewhere...
diff --git a/src/windows/system.rs b/src/windows/system.rs
--- a/src/windows/system.rs
+++ b/src/windows/system.rs
@@ -122,101 +121,6 @@ impl SystemExt for System {
}
}
}
-
- if let Some(network_trans) = get_translation(&"Network Interface".to_owned(), &x) {
- let network_in_trans = get_translation(&"Bytes Received/Sec".to_owned(), &x);
- let network_out_trans = get_translation(&"Bytes Sent/sec".to_owned(), &x);
-
- const PERF_DETAIL_WIZARD: DWORD = 400;
- const PDH_MORE_DATA: DWORD = 0x800007D2;
-
- let mut network_trans_utf16: Vec<u16> = network_trans.encode_utf16().collect();
- network_trans_utf16.push(0);
- let mut dwCounterListSize: DWORD = 0;
- let mut dwInstanceListSize: DWORD = 0;
- let status = unsafe {
- PdhEnumObjectItemsW(
- ::std::ptr::null(),
- ::std::ptr::null(),
- network_trans_utf16.as_ptr(),
- ::std::ptr::null_mut(),
- &mut dwCounterListSize,
- ::std::ptr::null_mut(),
- &mut dwInstanceListSize,
- PERF_DETAIL_WIZARD,
- 0,
- )
- };
- if status != PDH_MORE_DATA as i32 {
- eprintln!("PdhEnumObjectItems invalid status: {:x}", status);
- } else {
- let mut pwsCounterListBuffer: Vec<u16> =
- Vec::with_capacity(dwCounterListSize as usize);
- let mut pwsInstanceListBuffer: Vec<u16> =
- Vec::with_capacity(dwInstanceListSize as usize);
- unsafe {
- pwsCounterListBuffer.set_len(dwCounterListSize as usize);
- pwsInstanceListBuffer.set_len(dwInstanceListSize as usize);
- }
- let status = unsafe {
- PdhEnumObjectItemsW(
- ::std::ptr::null(),
- ::std::ptr::null(),
- network_trans_utf16.as_ptr(),
- pwsCounterListBuffer.as_mut_ptr(),
- &mut dwCounterListSize,
- pwsInstanceListBuffer.as_mut_ptr(),
- &mut dwInstanceListSize,
- PERF_DETAIL_WIZARD,
- 0,
- )
- };
- if status != ERROR_SUCCESS as i32 {
- eprintln!("PdhEnumObjectItems invalid status: {:x}", status);
- } else {
- for (pos, x) in pwsInstanceListBuffer
- .split(|x| *x == 0)
- .filter(|x| x.len() > 0)
- .enumerate()
- {
- let net_interface = String::from_utf16(x).expect("invalid utf16");
- if let Some(ref network_in_trans) = network_in_trans {
- let mut key_in = None;
- add_counter(
- format!(
- "\\{}({})\\{}",
- network_trans, net_interface, network_in_trans
- ),
- query,
- &mut key_in,
- format!("net{}_in", pos),
- CounterValue::Integer(0),
- );
- if key_in.is_some() {
- network::get_keys_in(&mut s.network).push(key_in.unwrap());
- }
- }
- if let Some(ref network_out_trans) = network_out_trans {
- let mut key_out = None;
- add_counter(
- format!(
- "\\{}({})\\{}",
- network_trans, net_interface, network_out_trans
- ),
- query,
- &mut key_out,
- format!("net{}_out", pos),
- CounterValue::Integer(0),
- );
- if key_out.is_some() {
- network::get_keys_out(&mut s.network).push(key_out.unwrap());
- }
- }
- }
- }
- }
- }
- query.start();
}
s.refresh_specifics(refreshes);
s
diff --git a/src/windows/system.rs b/src/windows/system.rs
--- a/src/windows/system.rs
+++ b/src/windows/system.rs
@@ -231,7 +135,7 @@ impl SystemExt for System {
idle_time = Some(query.get(&key_idle.unique_id).expect("key disappeared"));
}
if let Some(idle_time) = idle_time {
- set_cpu_usage(p, 1. - idle_time);
+ p.set_cpu_usage(1. - idle_time);
}
}
}
diff --git a/src/windows/system.rs b/src/windows/system.rs
--- a/src/windows/system.rs
+++ b/src/windows/system.rs
@@ -250,18 +154,23 @@ impl SystemExt for System {
}
}
+ /// Refresh components' temperature.
+ ///
/// Please note that on Windows, you need to have Administrator priviledges to get this
/// information.
+ ///
+ /// ```no_run
+ /// use sysinfo::{System, SystemExt};
+ ///
+ /// let mut s = System::new();
+ /// s.refresh_temperatures();
+ /// ```
fn refresh_temperatures(&mut self) {
for component in &mut self.temperatures {
component.refresh();
}
}
- fn refresh_network(&mut self) {
- network::refresh(&mut self.network, &self.query);
- }
-
fn refresh_process(&mut self, pid: Pid) -> bool {
if refresh_existing_process(self, pid, true) == false {
self.process_list.remove(&pid);
diff --git a/src/windows/system.rs b/src/windows/system.rs
--- a/src/windows/system.rs
+++ b/src/windows/system.rs
@@ -379,7 +288,7 @@ impl SystemExt for System {
});
}
- fn refresh_disk_list(&mut self) {
+ fn refresh_disks_list(&mut self) {
self.disks = unsafe { get_disks() };
}
diff --git a/src/windows/system.rs b/src/windows/system.rs
--- a/src/windows/system.rs
+++ b/src/windows/system.rs
@@ -427,13 +336,21 @@ impl SystemExt for System {
&self.disks[..]
}
- fn get_network(&self) -> &NetworkData {
- &self.network
+ fn get_networks(&self) -> &Networks {
+ &self.networks
+ }
+
+ fn get_networks_mut(&mut self) -> &mut Networks {
+ &mut self.networks
}
fn get_uptime(&self) -> u64 {
self.uptime
}
+
+ fn get_load_average(&self) -> LoadAvg {
+ get_load_average()
+ }
}
fn is_proc_running(handle: HANDLE) -> bool {
diff --git a/src/windows/tools.rs b/src/windows/tools.rs
--- a/src/windows/tools.rs
+++ b/src/windows/tools.rs
@@ -4,7 +4,7 @@
// Copyright (c) 2018 Guillaume Gomez
//
-use windows::processor::{create_processor, CounterValue, Processor, Query};
+use windows::processor::{self, CounterValue, Processor, Query};
use sys::disk::{new_disk, Disk, DiskType};
diff --git a/src/windows/tools.rs b/src/windows/tools.rs
--- a/src/windows/tools.rs
+++ b/src/windows/tools.rs
@@ -44,56 +44,25 @@ impl KeyHandler {
}
}
-/*#[allow(non_snake_case)]
-#[allow(unused)]
-unsafe fn browser() {
- use winapi::um::pdh::{PdhBrowseCountersA, PDH_BROWSE_DLG_CONFIG_A};
- use winapi::shared::winerror::ERROR_SUCCESS;
-
- let mut BrowseDlgData: PDH_BROWSE_DLG_CONFIG_A = ::std::mem::zeroed();
- let mut CounterPathBuffer: [i8; 255] = ::std::mem::zeroed();
- const PERF_DETAIL_WIZARD: u32 = 400;
- let text = b"Select a counter to monitor.\0";
-
- BrowseDlgData.set_IncludeInstanceIndex(FALSE as u32);
- BrowseDlgData.set_SingleCounterPerAdd(TRUE as u32);
- BrowseDlgData.set_SingleCounterPerDialog(TRUE as u32);
- BrowseDlgData.set_LocalCountersOnly(FALSE as u32);
- BrowseDlgData.set_WildCardInstances(TRUE as u32);
- BrowseDlgData.set_HideDetailBox(TRUE as u32);
- BrowseDlgData.set_InitializePath(FALSE as u32);
- BrowseDlgData.set_DisableMachineSelection(FALSE as u32);
- BrowseDlgData.set_IncludeCostlyObjects(FALSE as u32);
- BrowseDlgData.set_ShowObjectBrowser(FALSE as u32);
- BrowseDlgData.hWndOwner = ::std::ptr::null_mut();
- BrowseDlgData.szReturnPathBuffer = CounterPathBuffer.as_mut_ptr();
- BrowseDlgData.cchReturnPathLength = 255;
- BrowseDlgData.pCallBack = None;
- BrowseDlgData.dwCallBackArg = 0;
- BrowseDlgData.CallBackStatus = ERROR_SUCCESS as i32;
- BrowseDlgData.dwDefaultDetailLevel = PERF_DETAIL_WIZARD;
- BrowseDlgData.szDialogBoxCaption = text as *const _ as usize as *mut i8;
- let ret = PdhBrowseCountersA(&mut BrowseDlgData as *mut _);
- println!("browser: {:?}", ret);
- for x in CounterPathBuffer.iter() {
- print!("{:?} ", *x);
- }
- println!("");
- for x in 0..256 {
- print!("{:?} ", *BrowseDlgData.szReturnPathBuffer.offset(x));
- }
- println!("");
-}*/
-
pub fn init_processors() -> Vec<Processor> {
unsafe {
let mut sys_info: SYSTEM_INFO = zeroed();
GetSystemInfo(&mut sys_info);
+ let (vendor_id, brand) = processor::get_vendor_id_and_brand(&sys_info);
+ let frequencies = processor::get_frequencies(sys_info.dwNumberOfProcessors as usize);
let mut ret = Vec::with_capacity(sys_info.dwNumberOfProcessors as usize + 1);
for nb in 0..sys_info.dwNumberOfProcessors {
- ret.push(create_processor(&format!("CPU {}", nb + 1)));
+ ret.push(Processor::new_with_values(
+ &format!("CPU {}", nb + 1),
+ vendor_id.clone(),
+ brand.clone(),
+ frequencies[nb as usize],
+ ));
}
- ret.insert(0, create_processor("Total CPU"));
+ ret.insert(
+ 0,
+ Processor::new_with_values("Total CPU", vendor_id, brand, 0),
+ );
ret
}
}
|
4ae1791d21f84f911ca8a77e3ebc19996b7de808
|
Feature Request: support retrieve CPU number and load info
Thanks for providing the awesome library for retrieving system information. But some information cannot be retrieved by this crate, like CPU number and CPU average load. (So I must use another crate like https://docs.rs/sys-info/0.5.8/sys_info/index.html).
If this crate can provide a full feature, it's will be great.
Thanks to all authors and contributors for this repo.
|
0.10
| 245
|
Ah indeed. I'll check if it's available as well on windows and OSX, otherwise I'll have a bit more work to do for them.
|
4ae1791d21f84f911ca8a77e3ebc19996b7de808
|
[
"system::tests::test_refresh_process"
] |
[
"system::tests::test_refresh_system",
"system::tests::test_get_process",
"system::tests::check_if_send_and_sync",
"test::check_memory_usage",
"test_disks",
"test_process",
"test_uptime",
"src/sysinfo.rs - (line 14)"
] |
[] |
[] |
2022-01-17T17:26:04Z
|
diff --git a/tests/process.rs b/tests/process.rs
--- a/tests/process.rs
+++ b/tests/process.rs
@@ -245,6 +245,8 @@ fn cpu_usage_is_not_nan() {
#[test]
fn test_process_times() {
+ use std::time::{SystemTime, UNIX_EPOCH};
+
if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
return;
}
diff --git a/tests/process.rs b/tests/process.rs
--- a/tests/process.rs
+++ b/tests/process.rs
@@ -275,6 +277,16 @@ fn test_process_times() {
assert!(p.run_time() >= 1);
assert!(p.run_time() <= 2);
assert!(p.start_time() > p.run_time());
+ // On linux, for whatever reason, the uptime seems to be older than the boot time, leading
+ // to this weird `+ 3` to ensure the test is passing as it should...
+ assert!(
+ p.start_time() + 3
+ > SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs(),
+ );
+ assert!(p.start_time() >= s.boot_time());
} else {
panic!("Process not found!");
}
|
[
"680"
] |
GuillaumeGomez__sysinfo-681
|
GuillaumeGomez/sysinfo
|
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -10,7 +10,7 @@ use std::str::FromStr;
use libc::{gid_t, kill, uid_t};
-use crate::sys::system::REMAINING_FILES;
+use crate::sys::system::{SystemInfo, REMAINING_FILES};
use crate::sys::utils::{get_all_data, get_all_data_from_file, realpath};
use crate::utils::into_iter;
use crate::{DiskUsage, Pid, ProcessExt, ProcessRefreshKind, ProcessStatus, Signal};
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -82,6 +82,7 @@ pub struct Process {
stime: u64,
old_utime: u64,
old_stime: u64,
+ start_time_without_boot_time: u64,
start_time: u64,
run_time: u64,
pub(crate) updated: bool,
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -101,7 +102,12 @@ pub struct Process {
}
impl Process {
- pub(crate) fn new(pid: Pid, parent: Option<Pid>, start_time: u64) -> Process {
+ pub(crate) fn new(
+ pid: Pid,
+ parent: Option<Pid>,
+ start_time_without_boot_time: u64,
+ info: &SystemInfo,
+ ) -> Process {
Process {
name: String::with_capacity(20),
pid,
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -119,7 +125,8 @@ impl Process {
old_utime: 0,
old_stime: 0,
updated: true,
- start_time,
+ start_time_without_boot_time,
+ start_time: start_time_without_boot_time + info.boot_time,
run_time: 0,
uid: 0,
gid: 0,
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -293,10 +300,9 @@ unsafe impl<'a, T> Sync for Wrap<'a, T> {}
pub(crate) fn _get_process_data(
path: &Path,
proc_list: &mut Process,
- page_size_kb: u64,
pid: Pid,
uptime: u64,
- clock_cycle: u64,
+ info: &SystemInfo,
refresh_kind: ProcessRefreshKind,
) -> Result<(Option<Process>, Pid), ()> {
let pid = match path.file_name().and_then(|x| x.to_str()).map(Pid::from_str) {
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -330,11 +336,10 @@ pub(crate) fn _get_process_data(
path,
entry,
&parts,
- page_size_kb,
parent_memory,
parent_virtual_memory,
uptime,
- clock_cycle,
+ info,
refresh_kind,
);
if refresh_kind.disk_usage() {
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -361,8 +366,9 @@ pub(crate) fn _get_process_data(
}
};
- let start_time = u64::from_str(parts[21]).unwrap_or(0) / clock_cycle;
- let mut p = Process::new(pid, parent_pid, start_time);
+ // To be noted that the start time is invalid here, it still needs
+ let start_time = u64::from_str(parts[21]).unwrap_or(0) / info.clock_cycle;
+ let mut p = Process::new(pid, parent_pid, start_time, info);
p.stat_file = stat_file;
get_status(&mut p, parts[2]);
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -419,11 +425,10 @@ pub(crate) fn _get_process_data(
path,
&mut p,
&parts,
- page_size_kb,
proc_list.memory,
proc_list.virtual_memory,
uptime,
- clock_cycle,
+ info,
refresh_kind,
);
if refresh_kind.disk_usage() {
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -437,16 +442,15 @@ fn update_time_and_memory(
path: &Path,
entry: &mut Process,
parts: &[&str],
- page_size_kb: u64,
parent_memory: u64,
parent_virtual_memory: u64,
uptime: u64,
- clock_cycle: u64,
+ info: &SystemInfo,
refresh_kind: ProcessRefreshKind,
) {
{
// rss
- entry.memory = u64::from_str(parts[23]).unwrap_or(0) * page_size_kb;
+ entry.memory = u64::from_str(parts[23]).unwrap_or(0) * info.page_size_kb;
if entry.memory >= parent_memory {
entry.memory -= parent_memory;
}
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -460,15 +464,14 @@ fn update_time_and_memory(
u64::from_str(parts[13]).unwrap_or(0),
u64::from_str(parts[14]).unwrap_or(0),
);
- entry.run_time = uptime.saturating_sub(entry.start_time);
+ entry.run_time = uptime.saturating_sub(entry.start_time_without_boot_time);
}
refresh_procs(
entry,
&path.join("task"),
- page_size_kb,
entry.pid,
uptime,
- clock_cycle,
+ info,
refresh_kind,
);
}
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -476,10 +479,9 @@ fn update_time_and_memory(
pub(crate) fn refresh_procs(
proc_list: &mut Process,
path: &Path,
- page_size_kb: u64,
pid: Pid,
uptime: u64,
- clock_cycle: u64,
+ info: &SystemInfo,
refresh_kind: ProcessRefreshKind,
) -> bool {
if let Ok(d) = fs::read_dir(path) {
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -509,10 +511,9 @@ pub(crate) fn refresh_procs(
if let Ok((p, _)) = _get_process_data(
e.as_path(),
proc_list.get(),
- page_size_kb,
pid,
uptime,
- clock_cycle,
+ info,
refresh_kind,
) {
p
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -526,15 +527,9 @@ pub(crate) fn refresh_procs(
let new_tasks = folders
.iter()
.filter_map(|e| {
- if let Ok((p, pid)) = _get_process_data(
- e.as_path(),
- proc_list,
- page_size_kb,
- pid,
- uptime,
- clock_cycle,
- refresh_kind,
- ) {
+ if let Ok((p, pid)) =
+ _get_process_data(e.as_path(), proc_list, pid, uptime, info, refresh_kind)
+ {
updated_pids.push(pid);
p
} else {
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -97,6 +97,22 @@ fn boot_time() -> u64 {
}
}
+pub(crate) struct SystemInfo {
+ pub(crate) page_size_kb: u64,
+ pub(crate) clock_cycle: u64,
+ pub(crate) boot_time: u64,
+}
+
+impl SystemInfo {
+ fn new() -> Self {
+ Self {
+ page_size_kb: unsafe { sysconf(_SC_PAGESIZE) / 1024 } as _,
+ clock_cycle: unsafe { sysconf(_SC_CLK_TCK) } as _,
+ boot_time: boot_time(),
+ }
+ }
+}
+
declare_signals! {
c_int,
Signal::Hangup => libc::SIGHUP,
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -146,18 +162,16 @@ pub struct System {
swap_free: u64,
global_processor: Processor,
processors: Vec<Processor>,
- page_size_kb: u64,
components: Vec<Component>,
disks: Vec<Disk>,
networks: Networks,
users: Vec<User>,
- boot_time: u64,
/// Field set to `false` in `update_processors` and to `true` in `refresh_processes_specifics`.
///
/// The reason behind this is to avoid calling the `update_processors` more than necessary.
/// For example when running `refresh_all` or `refresh_specifics`.
need_processors_update: bool,
- clock_cycle: u64,
+ info: SystemInfo,
}
impl System {
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -311,8 +325,10 @@ impl SystemExt for System {
const SUPPORTED_SIGNALS: &'static [Signal] = supported_signals();
fn new_with_specifics(refreshes: RefreshKind) -> System {
+ let info = SystemInfo::new();
+ let process_list = Process::new(Pid(0), None, 0, &info);
let mut s = System {
- process_list: Process::new(Pid(0), None, 0),
+ process_list,
mem_total: 0,
mem_free: 0,
mem_available: 0,
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -338,14 +354,12 @@ impl SystemExt for System {
String::new(),
),
processors: Vec::with_capacity(4),
- page_size_kb: unsafe { sysconf(_SC_PAGESIZE) / 1024 } as _,
components: Vec::new(),
disks: Vec::with_capacity(2),
networks: Networks::new(),
users: Vec::new(),
- boot_time: boot_time(),
need_processors_update: true,
- clock_cycle: unsafe { sysconf(_SC_CLK_TCK) } as _,
+ info,
};
s.refresh_specifics(refreshes);
s
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -389,10 +403,9 @@ impl SystemExt for System {
if refresh_procs(
&mut self.process_list,
Path::new("/proc"),
- self.page_size_kb,
Pid(0),
uptime,
- self.clock_cycle,
+ &self.info,
refresh_kind,
) {
self.clear_procs(refresh_kind);
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -405,10 +418,9 @@ impl SystemExt for System {
let found = match _get_process_data(
&Path::new("/proc/").join(pid.to_string()),
&mut self.process_list,
- self.page_size_kb,
Pid(0),
uptime,
- self.clock_cycle,
+ &self.info,
refresh_kind,
) {
Ok((Some(p), pid)) => {
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -539,7 +551,7 @@ impl SystemExt for System {
}
fn boot_time(&self) -> u64 {
- self.boot_time
+ self.info.boot_time
}
fn load_average(&self) -> LoadAvg {
diff --git a/src/windows/tools.rs b/src/windows/tools.rs
--- a/src/windows/tools.rs
+++ b/src/windows/tools.rs
@@ -95,7 +95,7 @@ pub unsafe fn get_disks() -> Vec<Disk> {
#[cfg(feature = "multithread")]
use rayon::iter::ParallelIterator;
- crate::utils::into_iter(0..size_of::<DWORD>() * 8)
+ crate::utils::into_iter(0..DWORD::BITS)
.filter_map(|x| {
if (drives >> x) & 1 == 0 {
return None;
|
c1a6c6f2c438d7cf4c947f555df3d6d408ef0fe4
|
On Linux `ProcessExt::start_time()` does not return the time since the epoch as documented
It seems to just return `(22) starttime` from `/proc/[pid]/stat`, see `man proc`: "The time the process started after system boot."
`info.process(get_current_pid().unwrap()).unwrap().start_time()` is much smaller than the expected 1642369341.
Note that just adding `boot_time()` only works half the time and is otherwise off by one second, are fractions lost somewhere along the way?
info.process(get_current_pid().unwrap()).unwrap().start_time() + info.boot_time() = 1642369340
SystemTime::now().duration_since(UNIX_EPOCH).unwrap() = 1642369341
|
0.22
| 681
|
It's pretty bad in any case. Interested into sending a PR? Otherwise I'll try to fix it as soon as possible.
|
c1a6c6f2c438d7cf4c947f555df3d6d408ef0fe4
|
[
"test_process_times"
] |
[
"common::tests::check_display_impl_process_status",
"system::tests::check_hostname_has_no_nuls",
"linux::system::test::lsb_release_fallback_not_android",
"linux::network::test::refresh_networks_list_add_interface",
"linux::network::test::refresh_networks_list_remove_interface",
"test::check_host_name",
"test::check_nb_supported_signals",
"test::check_memory_usage",
"test::check_system_info",
"test::ensure_is_supported_is_set_correctly",
"test::check_uid_gid",
"system::tests::test_refresh_system",
"system::tests::test_refresh_process",
"test::check_refresh_process_return_value",
"test::check_processors_number",
"test::check_process_memory_usage",
"system::tests::check_if_send_and_sync",
"system::tests::test_get_process",
"test::check_users",
"test::check_processes_cpu_usage",
"system::tests::check_uptime",
"test_disks",
"code_checkers::code_checks",
"test_networks",
"test_process_refresh",
"cpu_usage_is_not_nan",
"test_process",
"test_process_disk_usage",
"test_cmd",
"test_cwd",
"test_environ",
"test_physical_core_numbers",
"test_processor",
"test_send_sync",
"test_uptime",
"src/common.rs - common::DiskType (line 408) - compile",
"src/common.rs - common::LoadAvg (line 547) - compile",
"src/common.rs - common::DiskUsage (line 661) - compile",
"src/common.rs - common::NetworksIter (line 371) - compile",
"src/common.rs - common::Pid (line 87)",
"src/common.rs - common::PidExt (line 11)",
"src/common.rs - common::RefreshKind::networks_list (line 349)",
"src/common.rs - common::RefreshKind::with_memory (line 357)",
"src/common.rs - common::RefreshKind::components_list (line 360)",
"src/common.rs - common::RefreshKind::everything (line 263)",
"src/common.rs - common::RefreshKind::networks (line 348)",
"src/common.rs - common::RefreshKind::users_list (line 366)",
"src/common.rs - common::RefreshKind::with_components (line 359)",
"src/common.rs - common::ProcessRefreshKind::cpu (line 202)",
"src/common.rs - common::RefreshKind::with_disks_list (line 356)",
"src/common.rs - common::ProcessRefreshKind::without_disk_usage (line 203)",
"src/common.rs - common::RefreshKind::components (line 359)",
"src/common.rs - common::PidExt::from_u32 (line 29)",
"src/common.rs - common::RefreshKind::with_cpu (line 358)",
"src/common.rs - common::ProcessRefreshKind::without_cpu (line 202)",
"src/common.rs - common::RefreshKind::with_components_list (line 360)",
"src/common.rs - common::ProcessRefreshKind::disk_usage (line 203)",
"src/common.rs - common::ProcessRefreshKind::with_disk_usage (line 203)",
"src/common.rs - common::RefreshKind::with_disks (line 355)",
"src/common.rs - common::RefreshKind::processes (line 296)",
"src/common.rs - common::get_current_pid (line 796) - compile",
"src/lib.rs - doctest::process_clone (line 138) - compile",
"src/common.rs - common::PidExt::as_u32 (line 20)",
"src/common.rs - common::ProcessRefreshKind::with_cpu (line 202)",
"src/lib.rs - doctest::process_clone (line 147) - compile fail",
"src/common.rs - common::RefreshKind::disks_list (line 356)",
"src/common.rs - common::User (line 625) - compile",
"src/lib.rs - doctest::system_clone (line 160) - compile",
"src/lib.rs - doctest::system_clone (line 168) - compile fail",
"src/linux/network.rs - linux::network::Networks (line 12) - compile",
"src/common.rs - common::ProcessRefreshKind::everything (line 185)",
"src/lib.rs - set_open_files_limit (line 94) - compile",
"src/common.rs - common::RefreshKind::new (line 241)",
"src/common.rs - common::RefreshKind::disks (line 355)",
"src/common.rs - common::ProcessRefreshKind (line 147)",
"src/common.rs - common::ProcessRefreshKind::new (line 171)",
"src/common.rs - common::RefreshKind::cpu (line 358)",
"src/common.rs - common::RefreshKind::memory (line 357)",
"src/traits.rs - traits::ComponentExt::critical (line 1395) - compile",
"src/traits.rs - traits::ComponentExt::refresh (line 1419) - compile",
"src/traits.rs - traits::DiskExt (line 19) - compile",
"src/traits.rs - traits::DiskExt::mount_point (line 66) - compile",
"src/traits.rs - traits::DiskExt::is_removable (line 102) - compile",
"src/traits.rs - traits::ComponentExt::label (line 1407) - compile",
"src/traits.rs - traits::DiskExt::file_system (line 54) - compile",
"src/traits.rs - traits::ComponentExt::temperature (line 1371) - compile",
"src/traits.rs - traits::DiskExt::name (line 42) - compile",
"src/traits.rs - traits::DiskExt::refresh (line 114) - compile",
"src/traits.rs - traits::ComponentExt::max (line 1383) - compile",
"src/traits.rs - traits::DiskExt::available_space (line 90) - compile",
"src/traits.rs - traits::DiskExt::type_ (line 30) - compile",
"src/traits.rs - traits::NetworkExt::errors_on_received (line 1278) - compile",
"src/traits.rs - traits::NetworkExt::errors_on_transmitted (line 1304) - compile",
"src/traits.rs - traits::DiskExt::total_space (line 78) - compile",
"src/traits.rs - traits::NetworkExt::packets_transmitted (line 1252) - compile",
"src/traits.rs - traits::NetworkExt::packets_received (line 1226) - compile",
"src/traits.rs - traits::NetworkExt::transmitted (line 1200) - compile",
"src/traits.rs - traits::NetworkExt::total_errors_on_received (line 1291) - compile",
"src/traits.rs - traits::NetworksExt::refresh (line 1357) - compile",
"src/traits.rs - traits::NetworkExt::received (line 1174) - compile",
"src/traits.rs - traits::NetworksExt::iter (line 1333) - compile",
"src/traits.rs - traits::NetworkExt::total_received (line 1187) - compile",
"src/traits.rs - traits::NetworkExt::total_packets_transmitted (line 1265) - compile",
"src/traits.rs - traits::NetworkExt::total_transmitted (line 1213) - compile",
"src/traits.rs - traits::NetworksExt::refresh_networks_list (line 1346) - compile",
"src/traits.rs - traits::ProcessExt::cpu_usage (line 342) - compile",
"src/traits.rs - traits::NetworkExt::total_errors_on_transmitted (line 1317) - compile",
"src/traits.rs - traits::NetworkExt::total_packets_received (line 1239) - compile",
"src/traits.rs - traits::ProcessExt::cwd (line 239) - compile",
"src/traits.rs - traits::ProcessExt::environ (line 227) - compile",
"src/traits.rs - traits::ProcessExt::disk_usage (line 356) - compile",
"src/traits.rs - traits::ProcessExt::cmd (line 191) - compile",
"src/traits.rs - traits::ProcessExt::pid (line 215) - compile",
"src/traits.rs - traits::ProcessExt::run_time (line 323) - compile",
"src/traits.rs - traits::ProcessExt::memory (line 263) - compile",
"src/traits.rs - traits::ProcessExt::root (line 251) - compile",
"src/traits.rs - traits::ProcessExt::exe (line 203) - compile",
"src/traits.rs - traits::ProcessExt::kill (line 135) - compile",
"src/traits.rs - traits::ProcessExt::name (line 179) - compile",
"src/traits.rs - traits::ProcessExt::kill_with (line 156) - compile",
"src/traits.rs - traits::ProcessExt::virtual_memory (line 275) - compile",
"src/traits.rs - traits::ProcessExt::status (line 299) - compile",
"src/traits.rs - traits::ProcessExt::parent (line 287) - compile",
"src/traits.rs - traits::ProcessExt::start_time (line 311) - compile",
"src/common.rs - common::RefreshKind (line 211)",
"src/traits.rs - traits::ProcessorExt::name (line 394) - compile",
"src/traits.rs - traits::ProcessorExt::brand (line 418) - compile",
"src/traits.rs - traits::SystemExt::available_memory (line 936) - compile",
"src/traits.rs - traits::SystemExt::free_memory (line 920) - compile",
"src/traits.rs - traits::ProcessorExt::frequency (line 430) - compile",
"src/traits.rs - traits::SystemExt::components (line 986) - compile",
"src/traits.rs - traits::SystemExt::disks_mut (line 1034) - compile",
"src/traits.rs - traits::SystemExt::free_swap (line 966) - compile",
"src/traits.rs - traits::SystemExt::components_mut (line 998) - compile",
"src/traits.rs - traits::ProcessorExt::vendor_id (line 406) - compile",
"src/traits.rs - traits::ProcessorExt::cpu_usage (line 382) - compile",
"src/common.rs - common::RefreshKind::with_processes (line 314)",
"src/common.rs - common::RefreshKind::without_components_list (line 360)",
"src/traits.rs - traits::SystemExt::host_name (line 1161) - compile",
"src/traits.rs - traits::SystemExt::disks (line 1010) - compile",
"src/traits.rs - traits::SystemExt::boot_time (line 1085) - compile",
"src/traits.rs - traits::SystemExt::global_processor_info (line 865) - compile",
"src/traits.rs - traits::SystemExt::networks (line 1046) - compile",
"src/traits.rs - traits::SystemExt::long_os_version (line 1149) - compile",
"src/traits.rs - traits::SystemExt::load_average (line 1095) - compile",
"src/traits.rs - traits::SystemExt::name (line 1113) - compile",
"src/traits.rs - traits::SystemExt::kernel_version (line 1125) - compile",
"src/traits.rs - traits::SystemExt::os_version (line 1137) - compile",
"src/traits.rs - traits::SystemExt::networks_mut (line 1064) - compile",
"src/traits.rs - traits::SystemExt::new (line 477) - compile",
"src/traits.rs - traits::SystemExt::new_all (line 492) - compile",
"src/common.rs - common::RefreshKind::without_networks_list (line 349)",
"src/traits.rs - traits::SystemExt::physical_core_count (line 894) - compile",
"src/traits.rs - traits::SystemExt::processes_by_name (line 815) - compile",
"src/traits.rs - traits::SystemExt::processes (line 788) - compile",
"src/traits.rs - traits::SystemExt::processes_by_exact_name (line 840) - compile",
"src/traits.rs - traits::SystemExt::processors (line 878) - compile",
"src/traits.rs - traits::SystemExt::refresh_all (line 773) - compile",
"src/traits.rs - traits::SystemExt::refresh_components_list (line 624) - compile",
"src/traits.rs - traits::SystemExt::process (line 800) - compile",
"src/common.rs - common::RefreshKind::with_networks (line 348)",
"src/traits.rs - traits::SystemExt::refresh_components (line 610) - compile",
"src/traits.rs - traits::SystemExt::refresh_cpu (line 600) - compile",
"src/common.rs - common::RefreshKind::without_components (line 359)",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 757) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks (line 691) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks_list (line 705) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes (line 639) - compile",
"src/traits.rs - traits::SystemExt::refresh_memory (line 590) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 734) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 748) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes_specifics (line 654) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 725) - compile",
"src/traits.rs - traits::SystemExt::refresh_process (line 668) - compile",
"src/traits.rs - traits::SystemExt::refresh_process_specifics (line 681) - compile",
"src/traits.rs - traits::SystemExt::refresh_system (line 576) - compile",
"src/common.rs - common::RefreshKind::without_cpu (line 358)",
"src/traits.rs - traits::SystemExt::uptime (line 1075) - compile",
"src/traits.rs - traits::SystemExt::total_memory (line 904) - compile",
"src/traits.rs - traits::SystemExt::used_memory (line 946) - compile",
"src/traits.rs - traits::SystemExt::used_swap (line 976) - compile",
"src/traits.rs - traits::SystemExt::refresh_users_list (line 715) - compile",
"src/traits.rs - traits::UserExt (line 1434) - compile",
"src/traits.rs - traits::SystemExt::users (line 1022) - compile",
"src/traits.rs - traits::SystemExt::total_swap (line 956) - compile",
"src/common.rs - common::RefreshKind::with_networks_list (line 349)",
"src/traits.rs - traits::UserExt::groups (line 1486) - compile",
"src/traits.rs - traits::UserExt::uid (line 1445) - compile",
"src/common.rs - common::RefreshKind::without_disks_list (line 356)",
"src/common.rs - common::RefreshKind::without_users_list (line 366)",
"src/traits.rs - traits::UserExt::gid (line 1462) - compile",
"src/traits.rs - traits::UserExt::name (line 1474) - compile",
"src/common.rs - common::RefreshKind::with_users_list (line 366)",
"src/common.rs - common::RefreshKind::without_networks (line 348)",
"src/traits.rs - traits::SystemExt::IS_SUPPORTED (line 446)",
"src/common.rs - common::RefreshKind::without_memory (line 357)",
"src/common.rs - common::RefreshKind::without_disks (line 355)",
"src/common.rs - common::RefreshKind::without_processes (line 331)",
"src/traits.rs - traits::SystemExt::SUPPORTED_SIGNALS (line 460)",
"src/lib.rs - (line 37)",
"src/traits.rs - traits::SystemExt::new_with_specifics (line 506)",
"src/traits.rs - traits::SystemExt::refresh_specifics (line 527)"
] |
[] |
[] |
2022-01-14T22:08:03Z
|
diff --git /dev/null b/tests/code_checkers/docs.rs
new file mode 100644
--- /dev/null
+++ b/tests/code_checkers/docs.rs
@@ -0,0 +1,135 @@
+// Take a look at the license at the top of the repository in the LICENSE file.
+
+use super::utils::{show_error, TestResult};
+use std::ffi::OsStr;
+use std::path::Path;
+
+fn to_correct_name(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+
+ for c in s.chars() {
+ if c.is_uppercase() {
+ if !out.is_empty() {
+ out.push('_');
+ }
+ out.push_str(c.to_lowercase().to_string().as_str());
+ } else {
+ out.push(c);
+ }
+ }
+ out
+}
+
+fn check_md_doc_path(p: &Path, md_line: &str, ty_line: &str) -> bool {
+ let parts = md_line.split("/").collect::<Vec<_>>();
+ if let Some(md_name) = parts.last().and_then(|n| n.split(".md").next()) {
+ if let Some(name) = ty_line
+ .split_whitespace()
+ .filter(|s| !s.is_empty())
+ .skip(2)
+ .next()
+ {
+ if let Some(name) = name
+ .split('<')
+ .next()
+ .and_then(|n| n.split('{').next())
+ .and_then(|n| n.split('(').next())
+ .and_then(|n| n.split(';').next())
+ {
+ let correct = to_correct_name(name);
+ if correct.as_str() == md_name {
+ return true;
+ }
+ show_error(
+ p,
+ &format!(
+ "Invalid markdown file name `{}`, should have been `{}`",
+ md_name, correct
+ ),
+ );
+ return false;
+ }
+ }
+ show_error(p, &format!("Cannot extract type name from `{}`", ty_line));
+ } else {
+ show_error(p, &format!("Cannot extract md name from `{}`", md_line));
+ }
+ return false;
+}
+
+fn check_doc_comments_before(p: &Path, lines: &[&str], start: usize) -> bool {
+ let mut found_docs = false;
+
+ for pos in (0..start).rev() {
+ let trimmed = lines[pos].trim();
+ if trimmed.starts_with("///") {
+ if !lines[start].trim().starts_with("pub enum ThreadStatus {") {
+ show_error(
+ p,
+ &format!(
+ "Types should use common documentation by using `#[doc = include_str!(` \
+ and by putting the markdown file in the `md_doc` folder instead of `{}`",
+ &lines[pos],
+ ),
+ );
+ return false;
+ }
+ return true;
+ } else if trimmed.starts_with("#[doc = include_str!(") {
+ found_docs = true;
+ if !check_md_doc_path(p, trimmed, lines[start]) {
+ return false;
+ }
+ } else if !trimmed.starts_with("#[") && !trimmed.starts_with("//") {
+ break;
+ }
+ }
+ if !found_docs {
+ show_error(
+ p,
+ &format!(
+ "Missing documentation for public item: `{}` (if it's not supposed to be a public \
+ item, use `pub(crate)` instead)",
+ lines[start],
+ ),
+ );
+ return false;
+ }
+ true
+}
+
+pub fn check_docs(content: &str, p: &Path) -> TestResult {
+ let mut res = TestResult {
+ nb_tests: 0,
+ nb_errors: 0,
+ };
+
+ // No need to check if we are in the `src` folder or if we are in a `ffi.rs` file.
+ if p.parent().unwrap().file_name().unwrap() == OsStr::new("src")
+ || p.file_name().unwrap() == OsStr::new("ffi.rs")
+ {
+ return res;
+ }
+ let lines = content.lines().collect::<Vec<_>>();
+
+ for pos in 1..lines.len() {
+ let line = lines[pos];
+ let trimmed = line.trim();
+ if trimmed.starts_with("//!") {
+ show_error(p, "There shouln't be inner doc comments (`//!`)");
+ res.nb_tests += 1;
+ res.nb_errors += 1;
+ continue;
+ } else if !line.starts_with("pub fn ")
+ && !trimmed.starts_with("pub struct ")
+ && !trimmed.starts_with("pub enum ")
+ {
+ continue;
+ }
+ res.nb_tests += 1;
+ if !check_doc_comments_before(p, &lines, pos) {
+ res.nb_errors += 1;
+ }
+ }
+ res
+}
diff --git a/tests/code_checkers/mod.rs b/tests/code_checkers/mod.rs
--- a/tests/code_checkers/mod.rs
+++ b/tests/code_checkers/mod.rs
@@ -1,5 +1,6 @@
// Take a look at the license at the top of the repository in the LICENSE file.
+mod docs;
mod headers;
mod signals;
mod utils;
diff --git a/tests/code_checkers/mod.rs b/tests/code_checkers/mod.rs
--- a/tests/code_checkers/mod.rs
+++ b/tests/code_checkers/mod.rs
@@ -10,6 +11,7 @@ use utils::TestResult;
const CHECKS: &[(fn(&str, &Path) -> TestResult, &[&str])] = &[
(headers::check_license_header, &["src", "tests", "examples"]),
(signals::check_signals, &["src"]),
+ (docs::check_docs, &["src"]),
];
fn handle_tests(res: &mut [TestResult]) {
|
[
"592"
] |
GuillaumeGomez__sysinfo-679
|
GuillaumeGomez/sysinfo
|
diff --git a/src/apple/macos/component.rs b/src/apple/macos/component.rs
--- a/src/apple/macos/component.rs
+++ b/src/apple/macos/component.rs
@@ -18,7 +18,7 @@ pub(crate) const COMPONENTS_TEMPERATURE_IDS: &[(&str, &[i8])] = &[
("Battery", &['T' as i8, 'B' as i8, '0' as i8, 'T' as i8]), // Battery "TB0T"
];
-pub struct ComponentFFI {
+pub(crate) struct ComponentFFI {
input_structure: ffi::KeyData_t,
val: ffi::Val_t,
}
diff --git a/src/apple/macos/system.rs b/src/apple/macos/system.rs
--- a/src/apple/macos/system.rs
+++ b/src/apple/macos/system.rs
@@ -16,7 +16,7 @@ unsafe fn free_cpu_load_info(cpu_load: &mut processor_cpu_load_info_t) {
}
}
-pub struct SystemTimeInfo {
+pub(crate) struct SystemTimeInfo {
timebase_to_ns: f64,
clock_per_sec: f64,
old_cpu_load: processor_cpu_load_info_t,
diff --git a/src/apple/processor.rs b/src/apple/processor.rs
--- a/src/apple/processor.rs
+++ b/src/apple/processor.rs
@@ -9,7 +9,7 @@ use std::mem;
use std::ops::Deref;
use std::sync::Arc;
-pub struct UnsafePtr<T>(*mut T);
+pub(crate) struct UnsafePtr<T>(*mut T);
unsafe impl<T> Send for UnsafePtr<T> {}
unsafe impl<T> Sync for UnsafePtr<T> {}
diff --git a/src/apple/processor.rs b/src/apple/processor.rs
--- a/src/apple/processor.rs
+++ b/src/apple/processor.rs
@@ -22,7 +22,7 @@ impl<T> Deref for UnsafePtr<T> {
}
}
-pub struct ProcessorData {
+pub(crate) struct ProcessorData {
pub cpu_info: UnsafePtr<i32>,
pub num_cpu_info: u32,
}
diff --git a/src/apple/processor.rs b/src/apple/processor.rs
--- a/src/apple/processor.rs
+++ b/src/apple/processor.rs
@@ -117,7 +117,7 @@ impl ProcessorExt for Processor {
}
}
-pub fn get_cpu_frequency() -> u64 {
+pub(crate) fn get_cpu_frequency() -> u64 {
let mut speed: u64 = 0;
let mut len = std::mem::size_of::<u64>();
unsafe {
diff --git a/src/apple/processor.rs b/src/apple/processor.rs
--- a/src/apple/processor.rs
+++ b/src/apple/processor.rs
@@ -192,7 +192,7 @@ pub(crate) fn update_processor_usage<F: FnOnce(Arc<ProcessorData>, *mut i32) ->
global_processor.set_cpu_usage(total_cpu_usage);
}
-pub fn init_processors(
+pub(crate) fn init_processors(
port: libc::mach_port_t,
processors: &mut Vec<Processor>,
global_processor: &mut Processor,
diff --git a/src/apple/processor.rs b/src/apple/processor.rs
--- a/src/apple/processor.rs
+++ b/src/apple/processor.rs
@@ -279,7 +279,7 @@ fn get_sysctl_str(s: &[u8]) -> String {
}
}
-pub fn get_vendor_id_and_brand() -> (String, String) {
+pub(crate) fn get_vendor_id_and_brand() -> (String, String) {
// On apple M1, `sysctl machdep.cpu.vendor` returns "", so fallback to "Apple" if the result
// is empty.
let mut vendor = get_sysctl_str(b"machdep.cpu.vendor\0");
diff --git a/src/apple/users.rs b/src/apple/users.rs
--- a/src/apple/users.rs
+++ b/src/apple/users.rs
@@ -83,7 +83,7 @@ where
users
}
-pub fn get_users_list() -> Vec<User> {
+pub(crate) fn get_users_list() -> Vec<User> {
users_list(|shell, uid| {
!endswith(shell, b"/false") && !endswith(shell, b"/uucico") && uid < 65536
})
diff --git a/src/apple/utils.rs b/src/apple/utils.rs
--- a/src/apple/utils.rs
+++ b/src/apple/utils.rs
@@ -2,11 +2,11 @@
use libc::c_char;
-pub fn cstr_to_rust(c: *const c_char) -> Option<String> {
+pub(crate) fn cstr_to_rust(c: *const c_char) -> Option<String> {
cstr_to_rust_with_size(c, None)
}
-pub fn cstr_to_rust_with_size(c: *const c_char, size: Option<usize>) -> Option<String> {
+pub(crate) fn cstr_to_rust_with_size(c: *const c_char, size: Option<usize>) -> Option<String> {
if c.is_null() {
return None;
}
diff --git a/src/freebsd/component.rs b/src/freebsd/component.rs
--- a/src/freebsd/component.rs
+++ b/src/freebsd/component.rs
@@ -3,7 +3,7 @@
use super::utils::get_sys_value_by_name;
use crate::ComponentExt;
-/// Dummy struct representing a component.
+#[doc = include_str!("../../md_doc/component.md")]
pub struct Component {
id: Vec<u8>,
label: String,
diff --git a/src/freebsd/disk.rs b/src/freebsd/disk.rs
--- a/src/freebsd/disk.rs
+++ b/src/freebsd/disk.rs
@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
use super::utils::c_buf_to_str;
-/// Struct containing a disk information.
+#[doc = include_str!("../../md_doc/disk.md")]
pub struct Disk {
name: OsString,
c_mount_point: Vec<libc::c_char>,
diff --git a/src/freebsd/processor.rs b/src/freebsd/processor.rs
--- a/src/freebsd/processor.rs
+++ b/src/freebsd/processor.rs
@@ -2,7 +2,7 @@
use crate::ProcessorExt;
-/// Dummy struct that represents a processor.
+#[doc = include_str!("../../md_doc/processor.md")]
pub struct Processor {
pub(crate) cpu_usage: f32,
name: String,
diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs
--- a/src/freebsd/utils.rs
+++ b/src/freebsd/utils.rs
@@ -10,7 +10,7 @@ use std::time::SystemTime;
/// This struct is used to switch between the "old" and "new" every time you use "get_mut".
#[derive(Debug)]
-pub struct VecSwitcher<T> {
+pub(crate) struct VecSwitcher<T> {
v1: Vec<T>,
v2: Vec<T>,
first: bool,
diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs
--- a/src/freebsd/utils.rs
+++ b/src/freebsd/utils.rs
@@ -61,7 +61,7 @@ pub unsafe fn init_mib(name: &[u8], mib: &mut [c_int]) {
libc::sysctlnametomib(name.as_ptr() as _, mib.as_mut_ptr(), &mut len);
}
-pub fn boot_time() -> u64 {
+pub(crate) fn boot_time() -> u64 {
let mut boot_time = timeval {
tv_sec: 0,
tv_usec: 0,
diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs
--- a/src/freebsd/utils.rs
+++ b/src/freebsd/utils.rs
@@ -109,7 +109,7 @@ pub unsafe fn get_sys_value_array<T: Sized>(mib: &[c_int], value: &mut [T]) -> b
) == 0
}
-pub fn c_buf_to_str(buf: &[libc::c_char]) -> Option<&str> {
+pub(crate) fn c_buf_to_str(buf: &[libc::c_char]) -> Option<&str> {
unsafe {
let buf: &[u8] = std::slice::from_raw_parts(buf.as_ptr() as _, buf.len());
if let Some(pos) = buf.iter().position(|x| *x == 0) {
diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs
--- a/src/freebsd/utils.rs
+++ b/src/freebsd/utils.rs
@@ -121,7 +121,7 @@ pub fn c_buf_to_str(buf: &[libc::c_char]) -> Option<&str> {
}
}
-pub fn c_buf_to_string(buf: &[libc::c_char]) -> Option<String> {
+pub(crate) fn c_buf_to_string(buf: &[libc::c_char]) -> Option<String> {
c_buf_to_str(buf).map(|s| s.to_owned())
}
diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs
--- a/src/freebsd/utils.rs
+++ b/src/freebsd/utils.rs
@@ -155,7 +155,7 @@ pub unsafe fn get_sys_value_by_name<T: Sized>(name: &[u8], value: &mut T) -> boo
&& original == len
}
-pub fn get_sys_value_str_by_name(name: &[u8]) -> Option<String> {
+pub(crate) fn get_sys_value_str_by_name(name: &[u8]) -> Option<String> {
let mut size = 0;
unsafe {
diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs
--- a/src/freebsd/utils.rs
+++ b/src/freebsd/utils.rs
@@ -191,7 +191,7 @@ pub fn get_sys_value_str_by_name(name: &[u8]) -> Option<String> {
}
}
-pub fn get_system_info(mib: &[c_int], default: Option<&str>) -> Option<String> {
+pub(crate) fn get_system_info(mib: &[c_int], default: Option<&str>) -> Option<String> {
let mut size = 0;
// Call first to get size
diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs
--- a/src/freebsd/utils.rs
+++ b/src/freebsd/utils.rs
@@ -258,7 +258,7 @@ pub unsafe fn from_cstr_array(ptr: *const *const c_char) -> Vec<String> {
ret
}
-pub fn get_now() -> u64 {
+pub(crate) fn get_now() -> u64 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|n| n.as_secs())
diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs
--- a/src/freebsd/utils.rs
+++ b/src/freebsd/utils.rs
@@ -266,19 +266,19 @@ pub fn get_now() -> u64 {
}
// All this is needed because `kinfo_proc` doesn't implement `Send` (because it contains pointers).
-pub struct WrapMap<'a>(pub UnsafeCell<&'a mut HashMap<Pid, Process>>);
+pub(crate) struct WrapMap<'a>(pub UnsafeCell<&'a mut HashMap<Pid, Process>>);
unsafe impl<'a> Send for WrapMap<'a> {}
unsafe impl<'a> Sync for WrapMap<'a> {}
-pub struct ProcList<'a>(pub &'a [libc::kinfo_proc]);
+pub(crate) struct ProcList<'a>(pub &'a [libc::kinfo_proc]);
unsafe impl<'a> Send for ProcList<'a> {}
-pub struct WrapItem<'a>(pub &'a libc::kinfo_proc);
+pub(crate) struct WrapItem<'a>(pub &'a libc::kinfo_proc);
unsafe impl<'a> Send for WrapItem<'a> {}
unsafe impl<'a> Sync for WrapItem<'a> {}
-pub struct IntoIter<'a>(std::slice::Iter<'a, libc::kinfo_proc>);
+pub(crate) struct IntoIter<'a>(std::slice::Iter<'a, libc::kinfo_proc>);
unsafe impl<'a> Send for IntoIter<'a> {}
impl<'a> std::iter::Iterator for IntoIter<'a> {
diff --git a/src/linux/component.rs b/src/linux/component.rs
--- a/src/linux/component.rs
+++ b/src/linux/component.rs
@@ -158,7 +158,7 @@ impl ComponentExt for Component {
}
}
-pub fn get_components() -> Vec<Component> {
+pub(crate) fn get_components() -> Vec<Component> {
let mut components = Vec::with_capacity(10);
if let Ok(dir) = read_dir(&Path::new("/sys/class/hwmon/")) {
for entry in dir.flatten() {
diff --git a/src/linux/disk.rs b/src/linux/disk.rs
--- a/src/linux/disk.rs
+++ b/src/linux/disk.rs
@@ -253,7 +253,7 @@ fn get_all_disks_inner(content: &str) -> Vec<Disk> {
.collect()
}
-pub fn get_all_disks() -> Vec<Disk> {
+pub(crate) fn get_all_disks() -> Vec<Disk> {
get_all_disks_inner(&get_all_data("/proc/mounts", 16_385).unwrap_or_default())
}
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -220,7 +220,7 @@ impl Drop for Process {
}
}
-pub fn compute_cpu_usage(p: &mut Process, total_time: f32, max_value: f32) {
+pub(crate) fn compute_cpu_usage(p: &mut Process, total_time: f32, max_value: f32) {
// First time updating the values without reference, wait for a second cycle to update cpu_usage
if p.old_utime == 0 && p.old_stime == 0 {
return;
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -235,7 +235,7 @@ pub fn compute_cpu_usage(p: &mut Process, total_time: f32, max_value: f32) {
.min(max_value);
}
-pub fn set_time(p: &mut Process, utime: u64, stime: u64) {
+pub(crate) fn set_time(p: &mut Process, utime: u64, stime: u64) {
p.old_utime = p.utime;
p.old_stime = p.stime;
p.utime = utime;
diff --git a/src/linux/processor.rs b/src/linux/processor.rs
--- a/src/linux/processor.rs
+++ b/src/linux/processor.rs
@@ -10,7 +10,7 @@ use crate::ProcessorExt;
/// Struct containing values to compute a CPU usage.
#[derive(Clone, Copy)]
-pub struct CpuValues {
+pub(crate) struct CpuValues {
user: u64,
nice: u64,
system: u64,
diff --git a/src/linux/processor.rs b/src/linux/processor.rs
--- a/src/linux/processor.rs
+++ b/src/linux/processor.rs
@@ -217,11 +217,11 @@ impl ProcessorExt for Processor {
}
}
-pub fn get_raw_times(p: &Processor) -> (u64, u64) {
+pub(crate) fn get_raw_times(p: &Processor) -> (u64, u64) {
(p.total_time, p.old_total_time)
}
-pub fn get_cpu_frequency(cpu_core_index: usize) -> u64 {
+pub(crate) fn get_cpu_frequency(cpu_core_index: usize) -> u64 {
let mut s = String::new();
if File::open(format!(
"/sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq",
diff --git a/src/linux/processor.rs b/src/linux/processor.rs
--- a/src/linux/processor.rs
+++ b/src/linux/processor.rs
@@ -257,7 +257,7 @@ pub fn get_cpu_frequency(cpu_core_index: usize) -> u64 {
.unwrap_or_default()
}
-pub fn get_physical_core_count() -> Option<usize> {
+pub(crate) fn get_physical_core_count() -> Option<usize> {
let mut s = String::new();
if let Err(_e) = File::open("/proc/cpuinfo").and_then(|mut f| f.read_to_string(&mut s)) {
sysinfo_debug!("Cannot read `/proc/cpuinfo` file: {:?}", _e);
diff --git a/src/linux/processor.rs b/src/linux/processor.rs
--- a/src/linux/processor.rs
+++ b/src/linux/processor.rs
@@ -292,7 +292,7 @@ pub fn get_physical_core_count() -> Option<usize> {
}
/// Returns the brand/vendor string for the first CPU (which should be the same for all CPUs).
-pub fn get_vendor_id_and_brand() -> (String, String) {
+pub(crate) fn get_vendor_id_and_brand() -> (String, String) {
let mut s = String::new();
if File::open("/proc/cpuinfo")
.and_then(|mut f| f.read_to_string(&mut s))
diff --git a/src/linux/utils.rs b/src/linux/utils.rs
--- a/src/linux/utils.rs
+++ b/src/linux/utils.rs
@@ -17,7 +17,7 @@ pub(crate) fn get_all_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Res
}
#[allow(clippy::useless_conversion)]
-pub fn realpath(original: &Path) -> std::path::PathBuf {
+pub(crate) fn realpath(original: &Path) -> std::path::PathBuf {
use libc::{c_char, lstat, stat, S_IFLNK, S_IFMT};
use std::fs;
use std::mem::MaybeUninit;
diff --git a/src/windows/component.rs b/src/windows/component.rs
--- a/src/windows/component.rs
+++ b/src/windows/component.rs
@@ -92,7 +92,7 @@ impl ComponentExt for Component {
}
}
-pub fn get_components() -> Vec<Component> {
+pub(crate) fn get_components() -> Vec<Component> {
match Component::new() {
Some(c) => vec![c],
None => Vec::new(),
diff --git a/src/windows/disk.rs b/src/windows/disk.rs
--- a/src/windows/disk.rs
+++ b/src/windows/disk.rs
@@ -8,7 +8,7 @@ use std::path::Path;
use winapi::um::fileapi::GetDiskFreeSpaceExW;
use winapi::um::winnt::ULARGE_INTEGER;
-pub fn new_disk(
+pub(crate) fn new_disk(
name: &OsStr,
mount_point: &[u16],
file_system: &[u8],
diff --git a/src/windows/process.rs b/src/windows/process.rs
--- a/src/windows/process.rs
+++ b/src/windows/process.rs
@@ -792,6 +792,7 @@ fn check_sub(a: u64, b: u64) -> u64 {
a - b
}
}
+
/// Before changing this function, you must consider the following:
/// https://github.com/GuillaumeGomez/sysinfo/issues/459
pub(crate) fn compute_cpu_usage(p: &mut Process, nb_processors: u64) {
diff --git a/src/windows/process.rs b/src/windows/process.rs
--- a/src/windows/process.rs
+++ b/src/windows/process.rs
@@ -871,11 +872,11 @@ pub(crate) fn compute_cpu_usage(p: &mut Process, nb_processors: u64) {
}
}
-pub fn get_handle(p: &Process) -> HANDLE {
+pub(crate) fn get_handle(p: &Process) -> HANDLE {
*p.handle
}
-pub fn update_disk_usage(p: &mut Process) {
+pub(crate) fn update_disk_usage(p: &mut Process) {
let mut counters = MaybeUninit::<IO_COUNTERS>::uninit();
let ret = unsafe { GetProcessIoCounters(*p.handle, counters.as_mut_ptr()) };
if ret == 0 {
diff --git a/src/windows/process.rs b/src/windows/process.rs
--- a/src/windows/process.rs
+++ b/src/windows/process.rs
@@ -889,7 +890,7 @@ pub fn update_disk_usage(p: &mut Process) {
}
}
-pub fn update_memory(p: &mut Process) {
+pub(crate) fn update_memory(p: &mut Process) {
unsafe {
let mut pmc: PROCESS_MEMORY_COUNTERS_EX = zeroed();
if GetProcessMemoryInfo(
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -160,7 +160,7 @@ impl Drop for InternalQuery {
}
}
-pub struct Query {
+pub(crate) struct Query {
internal: InternalQuery,
}
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -364,7 +364,7 @@ fn get_vendor_id_not_great(info: &SYSTEM_INFO) -> String {
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
-pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) {
+pub(crate) fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) {
#[cfg(target_arch = "x86")]
use std::arch::x86::__cpuid;
#[cfg(target_arch = "x86_64")]
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -433,11 +433,11 @@ pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) {
}
#[cfg(all(not(target_arch = "x86_64"), not(target_arch = "x86")))]
-pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) {
+pub(crate) fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) {
(get_vendor_id_not_great(info), String::new())
}
-pub fn get_key_used(p: &mut Processor) -> &mut Option<KeyHandler> {
+pub(crate) fn get_key_used(p: &mut Processor) -> &mut Option<KeyHandler> {
&mut p.key_used
}
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -446,7 +446,7 @@ pub fn get_key_used(p: &mut Processor) -> &mut Option<KeyHandler> {
// If your PC has 64 or fewer logical processors installed, the above code will work fine. However,
// if your PC has more than 64 logical processors installed, use GetActiveProcessorCount() or
// GetLogicalProcessorInformation() to determine the total number of logical processors installed.
-pub fn get_frequencies(nb_processors: usize) -> Vec<u64> {
+pub(crate) fn get_frequencies(nb_processors: usize) -> Vec<u64> {
let size = nb_processors * mem::size_of::<PROCESSOR_POWER_INFORMATION>();
let mut infos: Vec<PROCESSOR_POWER_INFORMATION> = Vec::with_capacity(nb_processors);
diff --git a/src/windows/processor.rs b/src/windows/processor.rs
--- a/src/windows/processor.rs
+++ b/src/windows/processor.rs
@@ -474,7 +474,7 @@ pub fn get_frequencies(nb_processors: usize) -> Vec<u64> {
}
}
-pub fn get_physical_core_count() -> Option<usize> {
+pub(crate) fn get_physical_core_count() -> Option<usize> {
// we cannot use the number of processors here to pre calculate the buf size
// GetLogicalProcessorInformationEx with RelationProcessorCore passed to it not only returns
// the logical cores but also numa nodes
diff --git a/src/windows/tools.rs b/src/windows/tools.rs
--- a/src/windows/tools.rs
+++ b/src/windows/tools.rs
@@ -25,18 +25,17 @@ use winapi::um::winioctl::{
};
use winapi::um::winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, HANDLE};
-pub struct KeyHandler {
+pub(crate) struct KeyHandler {
pub unique_id: String,
- pub win_key: Vec<u16>,
}
impl KeyHandler {
- pub fn new(unique_id: String, win_key: Vec<u16>) -> KeyHandler {
- KeyHandler { unique_id, win_key }
+ pub fn new(unique_id: String) -> KeyHandler {
+ KeyHandler { unique_id }
}
}
-pub fn init_processors() -> (Vec<Processor>, String, String) {
+pub(crate) fn init_processors() -> (Vec<Processor>, String, String) {
unsafe {
let mut sys_info: SYSTEM_INFO = zeroed();
GetSystemInfo(&mut sys_info);
diff --git a/src/windows/tools.rs b/src/windows/tools.rs
--- a/src/windows/tools.rs
+++ b/src/windows/tools.rs
@@ -214,7 +213,7 @@ pub unsafe fn get_disks() -> Vec<Disk> {
.collect::<Vec<_>>()
}
-pub fn add_english_counter(
+pub(crate) fn add_english_counter(
s: String,
query: &mut Query,
keys: &mut Option<KeyHandler>,
diff --git a/src/windows/tools.rs b/src/windows/tools.rs
--- a/src/windows/tools.rs
+++ b/src/windows/tools.rs
@@ -222,7 +221,7 @@ pub fn add_english_counter(
) {
let mut full = s.encode_utf16().collect::<Vec<_>>();
full.push(0);
- if query.add_english_counter(&counter_name, full.clone()) {
- *keys = Some(KeyHandler::new(counter_name, full));
+ if query.add_english_counter(&counter_name, full) {
+ *keys = Some(KeyHandler::new(counter_name));
}
}
diff --git a/src/windows/utils.rs b/src/windows/utils.rs
--- a/src/windows/utils.rs
+++ b/src/windows/utils.rs
@@ -5,12 +5,12 @@ use winapi::shared::minwindef::FILETIME;
use std::time::SystemTime;
#[inline]
-pub fn filetime_to_u64(f: FILETIME) -> u64 {
+pub(crate) fn filetime_to_u64(f: FILETIME) -> u64 {
(f.dwHighDateTime as u64) << 32 | (f.dwLowDateTime as u64)
}
#[inline]
-pub fn get_now() -> u64 {
+pub(crate) fn get_now() -> u64 {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|n| n.as_secs())
|
b1d66813b7a5f35832302e5ed3d4d85ab94e9464
|
Add check to ensure that types are using common md files and not manual doc comments
For example `System` or `Process`.
|
0.22
| 679
|
c1a6c6f2c438d7cf4c947f555df3d6d408ef0fe4
|
[
"code_checkers::code_checks"
] |
[
"common::tests::check_display_impl_process_status",
"system::tests::check_hostname_has_no_nuls",
"linux::network::test::refresh_networks_list_add_interface",
"linux::system::test::lsb_release_fallback_not_android",
"linux::network::test::refresh_networks_list_remove_interface",
"test::check_host_name",
"test::check_nb_supported_signals",
"test::check_memory_usage",
"test::check_system_info",
"test::ensure_is_supported_is_set_correctly",
"test::check_uid_gid",
"system::tests::test_refresh_system",
"test::check_processors_number",
"system::tests::test_refresh_process",
"test::check_refresh_process_return_value",
"test::check_process_memory_usage",
"system::tests::check_if_send_and_sync",
"system::tests::test_get_process",
"test::check_users",
"test::check_processes_cpu_usage",
"system::tests::check_uptime",
"test_disks",
"test_networks",
"test_process_refresh",
"test_process",
"cpu_usage_is_not_nan",
"test_process_disk_usage",
"test_cmd",
"test_environ",
"test_cwd",
"test_process_times",
"test_physical_core_numbers",
"test_processor",
"test_send_sync",
"test_uptime",
"src/common.rs - common::DiskType (line 408) - compile",
"src/common.rs - common::NetworksIter (line 371) - compile",
"src/common.rs - common::LoadAvg (line 547) - compile",
"src/common.rs - common::DiskUsage (line 661) - compile",
"src/common.rs - common::Pid (line 87)",
"src/common.rs - common::PidExt::from_u32 (line 29)",
"src/common.rs - common::ProcessRefreshKind::without_cpu (line 202)",
"src/common.rs - common::RefreshKind::cpu (line 358)",
"src/common.rs - common::ProcessRefreshKind::without_disk_usage (line 203)",
"src/common.rs - common::ProcessRefreshKind::new (line 171)",
"src/common.rs - common::ProcessRefreshKind::with_disk_usage (line 203)",
"src/common.rs - common::RefreshKind::components (line 359)",
"src/common.rs - common::ProcessRefreshKind::with_cpu (line 202)",
"src/common.rs - common::PidExt (line 11)",
"src/common.rs - common::ProcessRefreshKind::everything (line 185)",
"src/common.rs - common::RefreshKind::with_components_list (line 360)",
"src/common.rs - common::RefreshKind::memory (line 357)",
"src/common.rs - common::RefreshKind::with_memory (line 357)",
"src/common.rs - common::RefreshKind::processes (line 296)",
"src/common.rs - common::ProcessRefreshKind::cpu (line 202)",
"src/common.rs - common::RefreshKind::disks_list (line 356)",
"src/common.rs - common::ProcessRefreshKind::disk_usage (line 203)",
"src/common.rs - common::RefreshKind::everything (line 263)",
"src/common.rs - common::PidExt::as_u32 (line 20)",
"src/common.rs - common::RefreshKind::new (line 241)",
"src/common.rs - common::RefreshKind::disks (line 355)",
"src/common.rs - common::RefreshKind::networks_list (line 349)",
"src/common.rs - common::RefreshKind::with_disks (line 355)",
"src/common.rs - common::RefreshKind::users_list (line 366)",
"src/common.rs - common::RefreshKind::with_components (line 359)",
"src/common.rs - common::get_current_pid (line 796) - compile",
"src/common.rs - common::User (line 625) - compile",
"src/common.rs - common::RefreshKind::components_list (line 360)",
"src/common.rs - common::RefreshKind::with_cpu (line 358)",
"src/lib.rs - doctest::system_clone (line 160) - compile",
"src/lib.rs - doctest::process_clone (line 138) - compile",
"src/lib.rs - doctest::process_clone (line 147) - compile fail",
"src/common.rs - common::RefreshKind::networks (line 348)",
"src/lib.rs - doctest::system_clone (line 168) - compile fail",
"src/linux/network.rs - linux::network::Networks (line 12) - compile",
"src/traits.rs - traits::ComponentExt::label (line 1407) - compile",
"src/lib.rs - set_open_files_limit (line 94) - compile",
"src/traits.rs - traits::ComponentExt::critical (line 1395) - compile",
"src/traits.rs - traits::ComponentExt::refresh (line 1419) - compile",
"src/traits.rs - traits::DiskExt::available_space (line 90) - compile",
"src/traits.rs - traits::DiskExt (line 19) - compile",
"src/traits.rs - traits::ComponentExt::temperature (line 1371) - compile",
"src/traits.rs - traits::ComponentExt::max (line 1383) - compile",
"src/common.rs - common::RefreshKind::with_disks_list (line 356)",
"src/traits.rs - traits::DiskExt::file_system (line 54) - compile",
"src/traits.rs - traits::DiskExt::is_removable (line 102) - compile",
"src/traits.rs - traits::DiskExt::name (line 42) - compile",
"src/traits.rs - traits::DiskExt::mount_point (line 66) - compile",
"src/traits.rs - traits::DiskExt::refresh (line 114) - compile",
"src/traits.rs - traits::DiskExt::type_ (line 30) - compile",
"src/traits.rs - traits::DiskExt::total_space (line 78) - compile",
"src/traits.rs - traits::NetworkExt::errors_on_transmitted (line 1304) - compile",
"src/traits.rs - traits::NetworkExt::received (line 1174) - compile",
"src/traits.rs - traits::NetworkExt::errors_on_received (line 1278) - compile",
"src/traits.rs - traits::NetworkExt::packets_transmitted (line 1252) - compile",
"src/traits.rs - traits::NetworkExt::total_errors_on_received (line 1291) - compile",
"src/traits.rs - traits::NetworkExt::packets_received (line 1226) - compile",
"src/traits.rs - traits::NetworkExt::total_errors_on_transmitted (line 1317) - compile",
"src/traits.rs - traits::NetworkExt::total_packets_received (line 1239) - compile",
"src/traits.rs - traits::NetworkExt::total_packets_transmitted (line 1265) - compile",
"src/traits.rs - traits::NetworksExt::iter (line 1333) - compile",
"src/traits.rs - traits::ProcessExt::environ (line 227) - compile",
"src/traits.rs - traits::ProcessExt::cpu_usage (line 342) - compile",
"src/traits.rs - traits::NetworksExt::refresh (line 1357) - compile",
"src/traits.rs - traits::NetworkExt::transmitted (line 1200) - compile",
"src/traits.rs - traits::ProcessExt::cmd (line 191) - compile",
"src/traits.rs - traits::NetworkExt::total_received (line 1187) - compile",
"src/traits.rs - traits::NetworksExt::refresh_networks_list (line 1346) - compile",
"src/traits.rs - traits::ProcessExt::cwd (line 239) - compile",
"src/traits.rs - traits::NetworkExt::total_transmitted (line 1213) - compile",
"src/traits.rs - traits::ProcessExt::disk_usage (line 356) - compile",
"src/traits.rs - traits::ProcessExt::exe (line 203) - compile",
"src/traits.rs - traits::ProcessExt::kill (line 135) - compile",
"src/common.rs - common::RefreshKind (line 211)",
"src/traits.rs - traits::ProcessExt::kill_with (line 156) - compile",
"src/traits.rs - traits::ProcessExt::memory (line 263) - compile",
"src/traits.rs - traits::ProcessExt::parent (line 287) - compile",
"src/traits.rs - traits::ProcessExt::name (line 179) - compile",
"src/traits.rs - traits::ProcessorExt::brand (line 418) - compile",
"src/traits.rs - traits::ProcessExt::virtual_memory (line 275) - compile",
"src/traits.rs - traits::ProcessorExt::cpu_usage (line 382) - compile",
"src/traits.rs - traits::ProcessExt::pid (line 215) - compile",
"src/traits.rs - traits::ProcessExt::root (line 251) - compile",
"src/traits.rs - traits::ProcessExt::start_time (line 311) - compile",
"src/traits.rs - traits::ProcessorExt::frequency (line 430) - compile",
"src/traits.rs - traits::ProcessExt::status (line 299) - compile",
"src/traits.rs - traits::ProcessExt::run_time (line 323) - compile",
"src/traits.rs - traits::SystemExt::available_memory (line 936) - compile",
"src/traits.rs - traits::ProcessorExt::name (line 394) - compile",
"src/traits.rs - traits::SystemExt::free_memory (line 920) - compile",
"src/traits.rs - traits::SystemExt::components_mut (line 998) - compile",
"src/traits.rs - traits::SystemExt::kernel_version (line 1125) - compile",
"src/traits.rs - traits::SystemExt::components (line 986) - compile",
"src/traits.rs - traits::SystemExt::disks_mut (line 1034) - compile",
"src/traits.rs - traits::SystemExt::boot_time (line 1085) - compile",
"src/traits.rs - traits::SystemExt::free_swap (line 966) - compile",
"src/traits.rs - traits::SystemExt::disks (line 1010) - compile",
"src/traits.rs - traits::SystemExt::host_name (line 1161) - compile",
"src/traits.rs - traits::ProcessorExt::vendor_id (line 406) - compile",
"src/traits.rs - traits::SystemExt::global_processor_info (line 865) - compile",
"src/traits.rs - traits::SystemExt::load_average (line 1095) - compile",
"src/traits.rs - traits::SystemExt::name (line 1113) - compile",
"src/traits.rs - traits::SystemExt::long_os_version (line 1149) - compile",
"src/traits.rs - traits::SystemExt::new (line 477) - compile",
"src/traits.rs - traits::SystemExt::os_version (line 1137) - compile",
"src/traits.rs - traits::SystemExt::processes_by_exact_name (line 840) - compile",
"src/traits.rs - traits::SystemExt::networks_mut (line 1064) - compile",
"src/traits.rs - traits::SystemExt::networks (line 1046) - compile",
"src/traits.rs - traits::SystemExt::new_all (line 492) - compile",
"src/traits.rs - traits::SystemExt::process (line 800) - compile",
"src/traits.rs - traits::SystemExt::processes (line 788) - compile",
"src/traits.rs - traits::SystemExt::physical_core_count (line 894) - compile",
"src/common.rs - common::ProcessRefreshKind (line 147)",
"src/traits.rs - traits::SystemExt::processors (line 878) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 757) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks (line 691) - compile",
"src/traits.rs - traits::SystemExt::refresh_memory (line 590) - compile",
"src/traits.rs - traits::SystemExt::processes_by_name (line 815) - compile",
"src/traits.rs - traits::SystemExt::refresh_components_list (line 624) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks_list (line 705) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 725) - compile",
"src/traits.rs - traits::SystemExt::refresh_components (line 610) - compile",
"src/traits.rs - traits::SystemExt::refresh_cpu (line 600) - compile",
"src/traits.rs - traits::SystemExt::refresh_all (line 773) - compile",
"src/traits.rs - traits::SystemExt::refresh_process (line 668) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 734) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 748) - compile",
"src/traits.rs - traits::SystemExt::refresh_process_specifics (line 681) - compile",
"src/traits.rs - traits::SystemExt::total_memory (line 904) - compile",
"src/traits.rs - traits::SystemExt::refresh_system (line 576) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes_specifics (line 654) - compile",
"src/traits.rs - traits::SystemExt::refresh_users_list (line 715) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes (line 639) - compile",
"src/traits.rs - traits::SystemExt::total_swap (line 956) - compile",
"src/traits.rs - traits::SystemExt::used_memory (line 946) - compile",
"src/traits.rs - traits::SystemExt::used_swap (line 976) - compile",
"src/traits.rs - traits::SystemExt::uptime (line 1075) - compile",
"src/traits.rs - traits::SystemExt::users (line 1022) - compile",
"src/traits.rs - traits::UserExt (line 1434) - compile",
"src/traits.rs - traits::UserExt::uid (line 1445) - compile",
"src/traits.rs - traits::UserExt::name (line 1474) - compile",
"src/traits.rs - traits::UserExt::gid (line 1462) - compile",
"src/traits.rs - traits::UserExt::groups (line 1486) - compile",
"src/traits.rs - traits::SystemExt::IS_SUPPORTED (line 446)",
"src/common.rs - common::RefreshKind::with_networks (line 348)",
"src/common.rs - common::RefreshKind::with_processes (line 314)",
"src/common.rs - common::RefreshKind::without_components (line 359)",
"src/common.rs - common::RefreshKind::without_cpu (line 358)",
"src/common.rs - common::RefreshKind::without_networks (line 348)",
"src/common.rs - common::RefreshKind::with_networks_list (line 349)",
"src/common.rs - common::RefreshKind::without_networks_list (line 349)",
"src/common.rs - common::RefreshKind::without_disks_list (line 356)",
"src/common.rs - common::RefreshKind::without_components_list (line 360)",
"src/common.rs - common::RefreshKind::without_processes (line 331)",
"src/common.rs - common::RefreshKind::without_memory (line 357)",
"src/common.rs - common::RefreshKind::without_users_list (line 366)",
"src/common.rs - common::RefreshKind::without_disks (line 355)",
"src/common.rs - common::RefreshKind::with_users_list (line 366)",
"src/traits.rs - traits::SystemExt::SUPPORTED_SIGNALS (line 460)",
"src/traits.rs - traits::SystemExt::new_with_specifics (line 506)",
"src/traits.rs - traits::SystemExt::refresh_specifics (line 527)",
"src/lib.rs - (line 37)"
] |
[] |
[] |
|
2021-06-11T08:30:22Z
|
diff --git a/src/system.rs b/src/system.rs
--- a/src/system.rs
+++ b/src/system.rs
@@ -89,4 +89,15 @@ mod tests {
assert!(!hostname.contains('\u{0}'))
}
}
+
+ #[test]
+ fn check_uptime() {
+ let sys = System::new();
+ let uptime = sys.get_uptime();
+ if System::IS_SUPPORTED {
+ std::thread::sleep(std::time::Duration::from_millis(1000));
+ let new_uptime = sys.get_uptime();
+ assert!(uptime < new_uptime);
+ }
+ }
}
|
[
"508"
] |
GuillaumeGomez__sysinfo-509
|
GuillaumeGomez/sysinfo
|
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -121,7 +121,6 @@ pub struct System {
components: Vec<Component>,
disks: Vec<Disk>,
networks: Networks,
- uptime: u64,
users: Vec<User>,
boot_time: u64,
}
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -278,7 +277,6 @@ impl SystemExt for System {
components: Vec::new(),
disks: Vec::with_capacity(2),
networks: Networks::new(),
- uptime: get_uptime(),
users: Vec::new(),
boot_time: boot_time(),
};
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -294,7 +292,6 @@ impl SystemExt for System {
}
fn refresh_memory(&mut self) {
- self.uptime = get_uptime();
if let Ok(data) = get_all_data("/proc/meminfo", 16_385) {
for line in data.split('\n') {
let field = match line.split(':').next() {
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -319,18 +316,17 @@ impl SystemExt for System {
}
fn refresh_cpu(&mut self) {
- self.uptime = get_uptime();
self.refresh_processors(None);
}
fn refresh_processes(&mut self) {
- self.uptime = get_uptime();
+ let uptime = self.get_uptime();
if refresh_procs(
&mut self.process_list,
Path::new("/proc"),
self.page_size_kb,
0,
- self.uptime,
+ uptime,
get_secs_since_epoch(),
) {
self.clear_procs();
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -338,13 +334,13 @@ impl SystemExt for System {
}
fn refresh_process(&mut self, pid: Pid) -> bool {
- self.uptime = get_uptime();
+ let uptime = self.get_uptime();
let found = match _get_process_data(
&Path::new("/proc/").join(pid.to_string()),
&mut self.process_list,
self.page_size_kb,
0,
- self.uptime,
+ uptime,
get_secs_since_epoch(),
) {
Ok((Some(p), pid)) => {
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -456,7 +452,12 @@ impl SystemExt for System {
}
fn get_uptime(&self) -> u64 {
- self.uptime
+ let content = get_all_data("/proc/uptime", 50).unwrap_or_default();
+ content
+ .split('.')
+ .next()
+ .and_then(|t| t.parse().ok())
+ .unwrap_or_default()
}
fn get_boot_time(&self) -> u64 {
diff --git a/src/linux/system.rs b/src/linux/system.rs
--- a/src/linux/system.rs
+++ b/src/linux/system.rs
@@ -1037,15 +1038,6 @@ pub fn get_all_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Result<Str
get_all_data_from_file(&mut file, size)
}
-fn get_uptime() -> u64 {
- let content = get_all_data("/proc/uptime", 50).unwrap_or_default();
- content
- .split('.')
- .next()
- .and_then(|t| t.parse().ok())
- .unwrap_or_default()
-}
-
fn get_secs_since_epoch() -> u64 {
match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => n.as_secs(),
|
5c69175f028a5608093d31597b93031d165774c5
|
Uptime: To cache, or not to cache?
I've been looking into FreeBSD support this week (#433), and while trying to implement `SystemExt::get_uptime`, I found an inconsistency.
Linux uses whatever value was cached during the most recent refresh.
https://github.com/GuillaumeGomez/sysinfo/blob/f8574e459d0b1d65ed649cd0897b36422d449217/src/linux/system.rs#L458-L460
Apple and Windows re-compute the uptime each time it is called.
https://github.com/GuillaumeGomez/sysinfo/blob/f8574e459d0b1d65ed649cd0897b36422d449217/src/apple/system.rs#L451-L455
https://github.com/GuillaumeGomez/sysinfo/blob/f8574e459d0b1d65ed649cd0897b36422d449217/src/windows/system.rs#L391-L393
Which of these should be the intended behavior?
|
0.18
| 509
|
Linux should be updated to look like the others. Gonna send a PR which will also enforce this behaviour with a test (and thanks for working on freebsd!).
|
3aa83dc410ebe2f6d5063a095104ea6c6394507f
|
[
"system::tests::check_uptime"
] |
[
"linux::network::test::refresh_networks_list_add_interface",
"linux::system::test::lsb_release_fallback_not_android",
"linux::network::test::refresh_networks_list_remove_interface",
"test::ensure_is_supported_is_set_correctly",
"system::tests::check_hostname_has_no_nuls",
"test::check_host_name",
"test::check_processors_number",
"test::check_uid_gid",
"test::check_system_info",
"system::tests::test_refresh_system",
"test::check_refresh_process_return_value",
"system::tests::test_get_process",
"test::check_memory_usage",
"system::tests::check_if_send_and_sync",
"system::tests::test_refresh_process",
"test::check_users",
"test::check_cpu_usage",
"test_disks",
"test_processor",
"test_process_refresh",
"test_process_disk_usage",
"test_process",
"cpu_usage_is_not_nan",
"test_get_cmd_line",
"test_physical_core_numbers",
"test_send_sync",
"test_uptime",
"src/common.rs - common::DiskType (line 241) - compile",
"src/common.rs - common::DiskUsage (line 446) - compile",
"src/common.rs - common::NetworksIter (line 204) - compile",
"src/common.rs - common::LoadAvg (line 339) - compile",
"src/common.rs - common::RefreshKind::components (line 193)",
"src/common.rs - common::RefreshKind::with_memory (line 191)",
"src/common.rs - common::RefreshKind::everything (line 153)",
"src/common.rs - common::RefreshKind::components_list (line 194)",
"src/common.rs - common::RefreshKind::with_components_list (line 194)",
"src/common.rs - common::RefreshKind::with_disks (line 189)",
"src/common.rs - common::RefreshKind::users_list (line 199)",
"src/common.rs - common::RefreshKind::without_components (line 193)",
"src/common.rs - common::RefreshKind::memory (line 191)",
"src/common.rs - common::User (line 410) - compile",
"src/common.rs - common::RefreshKind::without_components_list (line 194)",
"src/common.rs - common::RefreshKind::without_processes (line 188)",
"src/common.rs - common::RefreshKind::without_disks_list (line 190)",
"src/common.rs - common::RefreshKind::with_components (line 193)",
"src/common.rs - common::RefreshKind::with_disks_list (line 190)",
"src/common.rs - common::RefreshKind::disks (line 189)",
"src/common.rs - common::RefreshKind::disks_list (line 190)",
"src/linux/network.rs - linux::network::Networks (line 16) - compile",
"src/common.rs - common::RefreshKind::without_networks (line 186)",
"src/common.rs - common::RefreshKind::processes (line 188)",
"src/common.rs - common::RefreshKind::with_networks_list (line 187)",
"src/traits.rs - traits::ComponentExt::get_label (line 1276) - compile",
"src/common.rs - common::RefreshKind::without_networks_list (line 187)",
"src/common.rs - common::RefreshKind::networks_list (line 187)",
"src/lib.rs - set_open_files_limit (line 161) - compile",
"src/traits.rs - traits::ComponentExt::get_max (line 1252) - compile",
"src/common.rs - common::RefreshKind::with_users_list (line 199)",
"src/common.rs - common::RefreshKind::networks (line 186)",
"src/traits.rs - traits::ComponentExt::get_temperature (line 1240) - compile",
"src/traits.rs - traits::ComponentExt::refresh (line 1288) - compile",
"src/traits.rs - traits::ComponentExt::get_critical (line 1264) - compile",
"src/common.rs - common::RefreshKind::with_networks (line 186)",
"src/common.rs - common::RefreshKind::without_disks (line 189)",
"src/common.rs - common::RefreshKind::with_cpu (line 192)",
"src/common.rs - common::RefreshKind::without_cpu (line 192)",
"src/traits.rs - traits::DiskExt::get_file_system (line 57) - compile",
"src/traits.rs - traits::DiskExt (line 22) - compile",
"src/common.rs - common::RefreshKind::with_processes (line 188)",
"src/traits.rs - traits::DiskExt::get_mount_point (line 69) - compile",
"src/traits.rs - traits::DiskExt::get_available_space (line 93) - compile",
"src/common.rs - common::RefreshKind::cpu (line 192)",
"src/common.rs - common::RefreshKind::without_memory (line 191)",
"src/common.rs - common::RefreshKind::new (line 131)",
"src/traits.rs - traits::DiskExt::get_name (line 45) - compile",
"src/traits.rs - traits::DiskExt::get_type (line 33) - compile",
"src/traits.rs - traits::DiskExt::get_total_space (line 81) - compile",
"src/traits.rs - traits::DiskExt::refresh (line 105) - compile",
"src/traits.rs - traits::NetworkExt::get_packets_received (line 1095) - compile",
"src/traits.rs - traits::NetworkExt::get_errors_on_received (line 1147) - compile",
"src/traits.rs - traits::NetworkExt::get_received (line 1043) - compile",
"src/traits.rs - traits::NetworkExt::get_packets_transmitted (line 1121) - compile",
"src/traits.rs - traits::NetworkExt::get_total_errors_on_received (line 1160) - compile",
"src/traits.rs - traits::NetworkExt::get_total_errors_on_transmitted (line 1186) - compile",
"src/traits.rs - traits::NetworkExt::get_total_received (line 1056) - compile",
"src/traits.rs - traits::NetworkExt::get_total_packets_transmitted (line 1134) - compile",
"src/traits.rs - traits::NetworkExt::get_total_packets_received (line 1108) - compile",
"src/traits.rs - traits::ProcessExt::disk_usage (line 309) - compile",
"src/traits.rs - traits::NetworkExt::get_total_transmitted (line 1082) - compile",
"src/traits.rs - traits::NetworkExt::get_errors_on_transmitted (line 1173) - compile",
"src/traits.rs - traits::NetworkExt::get_transmitted (line 1069) - compile",
"src/traits.rs - traits::NetworksExt::refresh (line 1226) - compile",
"src/traits.rs - traits::ProcessExt::exe (line 162) - compile",
"src/traits.rs - traits::NetworksExt::iter (line 1202) - compile",
"src/traits.rs - traits::ProcessExt::cpu_usage (line 295) - compile",
"src/traits.rs - traits::ProcessExt::cwd (line 202) - compile",
"src/traits.rs - traits::NetworksExt::refresh_networks_list (line 1215) - compile",
"src/traits.rs - traits::ProcessExt::cmd (line 150) - compile",
"src/traits.rs - traits::ProcessExt::kill (line 126) - compile",
"src/traits.rs - traits::ProcessExt::memory (line 228) - compile",
"src/traits.rs - traits::ProcessExt::environ (line 188) - compile",
"src/traits.rs - traits::ProcessExt::root (line 216) - compile",
"src/traits.rs - traits::ProcessExt::virtual_memory (line 240) - compile",
"src/traits.rs - traits::ProcessExt::start_time (line 276) - compile",
"src/traits.rs - traits::ProcessExt::parent (line 252) - compile",
"src/traits.rs - traits::ProcessExt::pid (line 174) - compile",
"src/common.rs - common::RefreshKind (line 101)",
"src/traits.rs - traits::ProcessorExt::get_brand (line 371) - compile",
"src/traits.rs - traits::ProcessExt::name (line 138) - compile",
"src/traits.rs - traits::ProcessExt::status (line 264) - compile",
"src/traits.rs - traits::ProcessorExt::get_cpu_usage (line 335) - compile",
"src/traits.rs - traits::SystemExt::get_boot_time (line 954) - compile",
"src/traits.rs - traits::ProcessorExt::get_name (line 347) - compile",
"src/traits.rs - traits::SystemExt::get_available_memory (line 805) - compile",
"src/traits.rs - traits::SystemExt::get_free_swap (line 835) - compile",
"src/traits.rs - traits::ProcessorExt::get_vendor_id (line 359) - compile",
"src/traits.rs - traits::ProcessorExt::get_frequency (line 383) - compile",
"src/traits.rs - traits::SystemExt::get_components (line 855) - compile",
"src/traits.rs - traits::SystemExt::get_global_processor_info (line 737) - compile",
"src/traits.rs - traits::SystemExt::get_components_mut (line 867) - compile",
"src/traits.rs - traits::SystemExt::get_disks (line 879) - compile",
"src/traits.rs - traits::SystemExt::get_free_memory (line 789) - compile",
"src/traits.rs - traits::SystemExt::get_host_name (line 1030) - compile",
"src/traits.rs - traits::SystemExt::get_disks_mut (line 903) - compile",
"src/traits.rs - traits::SystemExt::get_kernel_version (line 994) - compile",
"src/traits.rs - traits::SystemExt::get_load_average (line 964) - compile",
"src/traits.rs - traits::SystemExt::get_name (line 982) - compile",
"src/traits.rs - traits::SystemExt::get_networks_mut (line 933) - compile",
"src/traits.rs - traits::SystemExt::get_networks (line 915) - compile",
"src/traits.rs - traits::SystemExt::get_physical_core_count (line 763) - compile",
"src/traits.rs - traits::SystemExt::get_process_by_name (line 717) - compile",
"src/traits.rs - traits::SystemExt::new (line 420) - compile",
"src/traits.rs - traits::SystemExt::get_uptime (line 944) - compile",
"src/traits.rs - traits::SystemExt::get_used_memory (line 815) - compile",
"src/traits.rs - traits::SystemExt::get_users (line 891) - compile",
"src/traits.rs - traits::SystemExt::refresh_all (line 678) - compile",
"src/traits.rs - traits::SystemExt::get_processes (line 693) - compile",
"src/traits.rs - traits::SystemExt::get_used_swap (line 845) - compile",
"src/traits.rs - traits::SystemExt::get_total_memory (line 773) - compile",
"src/traits.rs - traits::SystemExt::get_process (line 705) - compile",
"src/traits.rs - traits::SystemExt::get_long_os_version (line 1018) - compile",
"src/traits.rs - traits::SystemExt::get_total_swap (line 825) - compile",
"src/traits.rs - traits::SystemExt::refresh_components (line 551) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks_list (line 610) - compile",
"src/traits.rs - traits::SystemExt::refresh_cpu (line 541) - compile",
"src/traits.rs - traits::SystemExt::refresh_memory (line 531) - compile",
"src/traits.rs - traits::SystemExt::get_os_version (line 1006) - compile",
"src/traits.rs - traits::SystemExt::refresh_components_list (line 565) - compile",
"src/traits.rs - traits::SystemExt::new_all (line 435) - compile",
"src/traits.rs - traits::SystemExt::get_processors (line 747) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks (line 596) - compile",
"src/lib.rs - (line 365)",
"src/traits.rs - traits::SystemExt::refresh_networks (line 630) - compile",
"src/traits.rs - traits::SystemExt::refresh_process (line 586) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 662) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 653) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 639) - compile",
"src/traits.rs - traits::SystemExt::refresh_system (line 517) - compile",
"src/traits.rs - traits::SystemExt::refresh_users_list (line 620) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes (line 575) - compile",
"src/utils.rs - utils::get_current_pid (line 58) - compile",
"src/traits.rs - traits::UserExt::get_groups (line 1355) - compile",
"src/traits.rs - traits::UserExt (line 1303) - compile",
"src/lib.rs - (line 360)",
"src/traits.rs - traits::UserExt::get_uid (line 1314) - compile",
"src/traits.rs - traits::UserExt::get_gid (line 1331) - compile",
"src/traits.rs - traits::UserExt::get_name (line 1343) - compile",
"src/traits.rs - traits::SystemExt::IS_SUPPORTED (line 399)",
"src/common.rs - common::RefreshKind::without_users_list (line 199)",
"src/traits.rs - traits::SystemExt::new_with_specifics (line 449)",
"src/lib.rs - (line 33)",
"src/traits.rs - traits::SystemExt::refresh_specifics (line 470)",
"src/lib.rs - (line 137)"
] |
[] |
[] |
2023-11-29T15:55:10Z
|
diff --git a/tests/process.rs b/tests/process.rs
--- a/tests/process.rs
+++ b/tests/process.rs
@@ -2,28 +2,6 @@
use sysinfo::{Pid, ProcessRefreshKind, System, UpdateKind};
-#[test]
-fn test_process() {
- let mut s = System::new();
- assert_eq!(s.processes().len(), 0);
- s.refresh_processes();
- if !sysinfo::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
- return;
- }
- assert!(!s.processes().is_empty());
- assert!(s
- .processes()
- .values()
- .all(|p| p.exe().as_os_str().is_empty()));
-
- let mut s = System::new();
- s.refresh_processes_specifics(ProcessRefreshKind::new().with_exe(UpdateKind::Always));
- assert!(s
- .processes()
- .values()
- .any(|p| !p.exe().as_os_str().is_empty()));
-}
-
#[test]
fn test_cwd() {
if !sysinfo::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
diff --git a/tests/process.rs b/tests/process.rs
--- a/tests/process.rs
+++ b/tests/process.rs
@@ -188,17 +166,13 @@ fn test_process_refresh() {
.process(sysinfo::get_current_pid().expect("failed to get current pid"))
.is_some());
+ assert!(s.processes().iter().all(|(_, p)| p.environ().is_empty()
+ && p.cwd().as_os_str().is_empty()
+ && p.cmd().is_empty()));
assert!(s
.processes()
.iter()
- .all(|(_, p)| p.exe().as_os_str().is_empty()
- && p.environ().is_empty()
- && p.cwd().as_os_str().is_empty()
- && p.cmd().is_empty()));
- assert!(s
- .processes()
- .iter()
- .any(|(_, p)| !p.name().is_empty() && p.memory() != 0));
+ .any(|(_, p)| !p.exe().as_os_str().is_empty() && !p.name().is_empty() && p.memory() != 0));
}
#[test]
|
[
"1141"
] |
GuillaumeGomez__sysinfo-1161
|
GuillaumeGomez/sysinfo
|
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -221,13 +221,14 @@ impl System {
/// It does the same as:
///
/// ```no_run
- /// # use sysinfo::{ProcessRefreshKind, System};
+ /// # use sysinfo::{ProcessRefreshKind, System, UpdateKind};
/// # let mut system = System::new();
/// system.refresh_processes_specifics(
/// ProcessRefreshKind::new()
/// .with_memory()
/// .with_cpu()
- /// .with_disk_usage(),
+ /// .with_disk_usage()
+ /// .with_exe(UpdateKind::OnlyIfNotSet),
/// );
/// ```
///
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -247,7 +248,8 @@ impl System {
ProcessRefreshKind::new()
.with_memory()
.with_cpu()
- .with_disk_usage(),
+ .with_disk_usage()
+ .with_exe(UpdateKind::OnlyIfNotSet),
);
}
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -273,7 +275,7 @@ impl System {
/// It is the same as calling:
///
/// ```no_run
- /// # use sysinfo::{Pid, ProcessRefreshKind, System};
+ /// # use sysinfo::{Pid, ProcessRefreshKind, System, UpdateKind};
/// # let mut system = System::new();
/// # let pid = Pid::from(0);
/// system.refresh_process_specifics(
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -281,7 +283,8 @@ impl System {
/// ProcessRefreshKind::new()
/// .with_memory()
/// .with_cpu()
- /// .with_disk_usage(),
+ /// .with_disk_usage()
+ /// .with_exe(UpdateKind::OnlyIfNotSet),
/// );
/// ```
///
diff --git a/src/common.rs b/src/common.rs
--- a/src/common.rs
+++ b/src/common.rs
@@ -302,7 +305,8 @@ impl System {
ProcessRefreshKind::new()
.with_memory()
.with_cpu()
- .with_disk_usage(),
+ .with_disk_usage()
+ .with_exe(UpdateKind::OnlyIfNotSet),
)
}
|
9fb48e65376a6b479e8f134d38c6b38068436804
|
Should `exe` be included in default process retrieval (and removed from `ProcessRefreshKind`)?
It seems to be a basic information that everyone might want all the time.
|
0.29
| 1,161
|
Another solution would be to just remove `refresh_process[es]`.
|
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
|
[
"test_process_refresh"
] |
[
"common::tests::check_display_impl_mac_address",
"common::tests::check_mac_address_is_unspecified_true",
"common::tests::check_mac_address_is_unspecified_false",
"common::tests::check_display_impl_process_status",
"common::tests::check_uid_gid_from_impls",
"system::tests::check_hostname_has_no_nuls",
"test::check_all_process_uids_resolvable",
"test::check_cpu_arch",
"system::tests::test_refresh_process",
"test::check_list",
"system::tests::test_refresh_system",
"test::check_macro_types",
"test::check_nb_supported_signals",
"test::check_host_name",
"test::check_memory_usage",
"test::check_system_info",
"test::ensure_is_supported_is_set_correctly",
"test::check_cpus_number",
"test::check_system_implemented_traits",
"unix::linux::network::test::refresh_networks_list_add_interface",
"unix::linux::system::test::lsb_release_fallback_not_android",
"unix::linux::network::test::refresh_networks_list_remove_interface",
"test::check_refresh_process_return_value",
"test::check_uid_gid",
"system::tests::check_if_send_and_sync",
"system::tests::test_get_process",
"test::check_cpu_frequency",
"test::check_refresh_process_update",
"test::check_process_memory_usage",
"test::check_cpu_usage",
"test::check_processes_cpu_usage",
"system::tests::check_uptime",
"test_physical_core_numbers",
"test_global_cpu_info_not_set",
"test_cpu",
"test_disks",
"code_checkers::code_checks",
"test_networks",
"test_wait_child",
"test_process_iterator_lifetimes",
"test_process_session_id",
"cpu_usage_is_not_nan",
"test_process_creds",
"test_process_specific_refresh",
"test_process_disk_usage",
"test_process_cpu_usage",
"test_cmd",
"test_cwd",
"test_process_times",
"test_wait_non_child",
"test_refresh_process",
"test_refresh_processes",
"test_environ",
"test_refresh_tasks",
"test_send_sync",
"test_uptime",
"src/common.rs - common::System::new_all (line 60) - compile",
"src/common.rs - common::System::new (line 45) - compile",
"src/common.rs - common::System::refresh_all (line 126) - compile",
"src/common.rs - common::System::refresh_cpu_frequency (line 175) - compile",
"src/common.rs - common::System::refresh_cpu_specifics (line 209) - compile",
"src/common.rs - common::System::refresh_cpu_usage (line 158) - compile",
"src/common.rs - common::System::refresh_cpu (line 195) - compile",
"src/common.rs - common::System::refresh_memory (line 138) - compile",
"src/common.rs - common::System::refresh_processes (line 223) - compile",
"src/lib.rs - doctest::process_clone (line 147) - compile fail",
"src/lib.rs - doctest::process_clone (line 138) - compile",
"src/lib.rs - (line 132) - compile",
"src/lib.rs - (line 97) - compile",
"src/lib.rs - doctest::system_clone (line 160) - compile",
"src/lib.rs - set_open_files_limit (line 90) - compile",
"src/lib.rs - doctest::system_clone (line 168) - compile fail",
"src/unix/linux/mod.rs - unix::linux::IS_SUPPORTED (line 61)",
"src/common.rs - common::System::new_with_specifics (line 74)",
"src/common.rs - common::System (line 18)",
"src/unix/linux/mod.rs - unix::linux::SUPPORTED_SIGNALS (line 63)",
"src/common.rs - common::System::refresh_specifics (line 97)",
"src/lib.rs - (line 38)"
] |
[] |
[] |
2022-12-07T10:58:49Z
|
diff --git a/tests/code_checkers/docs.rs b/tests/code_checkers/docs.rs
--- a/tests/code_checkers/docs.rs
+++ b/tests/code_checkers/docs.rs
@@ -38,8 +38,7 @@ fn check_md_doc_path(p: &Path, md_line: &str, ty_line: &str) -> bool {
show_error(
p,
&format!(
- "Invalid markdown file name `{}`, should have been `{}`",
- md_name, correct
+ "Invalid markdown file name `{md_name}`, should have been `{correct}`",
),
);
return false;
diff --git a/tests/code_checkers/headers.rs b/tests/code_checkers/headers.rs
--- a/tests/code_checkers/headers.rs
+++ b/tests/code_checkers/headers.rs
@@ -39,8 +39,7 @@ pub fn check_license_header(content: &str, p: &Path) -> TestResult {
show_error(
p,
&format!(
- "Expected license header at the top of the file (`{}`), found: `{}`",
- header, s
+ "Expected license header at the top of the file (`{header}`), found: `{s}`",
),
);
TestResult {
diff --git a/tests/process.rs b/tests/process.rs
--- a/tests/process.rs
+++ b/tests/process.rs
@@ -141,6 +141,57 @@ fn test_environ() {
}
}
+// Test to ensure that a process with a lot of environment variables doesn't get truncated.
+// More information in <https://github.com/GuillaumeGomez/sysinfo/issues/886>.
+#[test]
+fn test_big_environ() {
+ if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") {
+ return;
+ }
+ const SIZE: usize = 30_000;
+ let mut big_env = String::with_capacity(SIZE);
+ for _ in 0..SIZE {
+ big_env.push('a');
+ }
+ let mut p = if cfg!(target_os = "windows") {
+ std::process::Command::new("waitfor")
+ .arg("/t")
+ .arg("3")
+ .arg("EnvironSignal")
+ .stdout(std::process::Stdio::null())
+ .env("FOO", &big_env)
+ .spawn()
+ .unwrap()
+ } else {
+ std::process::Command::new("sleep")
+ .arg("3")
+ .stdout(std::process::Stdio::null())
+ .env("FOO", &big_env)
+ .spawn()
+ .unwrap()
+ };
+
+ let pid = Pid::from_u32(p.id() as _);
+ std::thread::sleep(std::time::Duration::from_secs(1));
+ let mut s = sysinfo::System::new();
+ s.refresh_processes();
+ p.kill().expect("Unable to kill process.");
+
+ let processes = s.processes();
+ let p = processes.get(&pid);
+
+ if let Some(p) = p {
+ assert_eq!(p.pid(), pid);
+ // FIXME: instead of ignoring the test on CI, try to find out what's wrong...
+ if std::env::var("APPLE_CI").is_err() {
+ let env = format!("FOO={big_env}");
+ assert!(p.environ().iter().any(|e| *e == env));
+ }
+ } else {
+ panic!("Process not found!");
+ }
+}
+
#[test]
fn test_process_refresh() {
let mut s = sysinfo::System::new();
|
[
"886"
] |
GuillaumeGomez__sysinfo-887
|
GuillaumeGomez/sysinfo
|
diff --git a/examples/simple.rs b/examples/simple.rs
--- a/examples/simple.rs
+++ b/examples/simple.rs
@@ -342,11 +342,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
let minutes = uptime / 60;
writeln!(
&mut io::stdout(),
- "{} days {} hours {} minutes ({} seconds in total)",
- days,
- hours,
- minutes,
- up,
+ "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
);
}
x if x.starts_with("refresh") => {
diff --git a/examples/simple.rs b/examples/simple.rs
--- a/examples/simple.rs
+++ b/examples/simple.rs
@@ -365,11 +361,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
if sys.refresh_process(pid) {
writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
} else {
- writeln!(
- &mut io::stdout(),
- "Process `{}` couldn't be updated...",
- pid
- );
+ writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
}
} else {
writeln!(&mut io::stdout(), "Invalid [pid] received...");
diff --git a/examples/simple.rs b/examples/simple.rs
--- a/examples/simple.rs
+++ b/examples/simple.rs
@@ -377,9 +369,8 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
} else {
writeln!(
&mut io::stdout(),
- "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
+ "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
list.",
- x
);
}
}
diff --git a/examples/simple.rs b/examples/simple.rs
--- a/examples/simple.rs
+++ b/examples/simple.rs
@@ -410,9 +401,8 @@ fn interpret_input(input: &str, sys: &mut System) -> bool {
e => {
writeln!(
&mut io::stdout(),
- "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \
+ "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
list.",
- e
);
}
}
diff --git a/src/linux/cpu.rs b/src/linux/cpu.rs
--- a/src/linux/cpu.rs
+++ b/src/linux/cpu.rs
@@ -427,8 +427,7 @@ impl CpuExt for Cpu {
pub(crate) fn get_cpu_frequency(cpu_core_index: usize) -> u64 {
let mut s = String::new();
if File::open(format!(
- "/sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq",
- cpu_core_index
+ "/sys/devices/system/cpu/cpu{cpu_core_index}/cpufreq/scaling_cur_freq",
))
.and_then(|mut f| f.read_to_string(&mut s))
.is_ok()
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -620,10 +620,12 @@ pub(crate) fn refresh_procs(
fn copy_from_file(entry: &Path) -> Vec<String> {
match File::open(entry) {
Ok(mut f) => {
- let mut data = vec![0; 16_384];
+ let mut data = Vec::with_capacity(16_384);
- if let Ok(size) = f.read(&mut data) {
- data.truncate(size);
+ if let Err(_e) = f.read_to_end(&mut data) {
+ sysinfo_debug!("Failed to read file in `copy_from_file`: {:?}", _e);
+ Vec::new()
+ } else {
let mut out = Vec::with_capacity(20);
let mut start = 0;
for (pos, x) in data.iter().enumerate() {
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -639,11 +641,12 @@ fn copy_from_file(entry: &Path) -> Vec<String> {
}
}
out
- } else {
- Vec::new()
}
}
- Err(_) => Vec::new(),
+ Err(_e) => {
+ sysinfo_debug!("Failed to open file in `copy_from_file`: {:?}", _e);
+ Vec::new()
+ }
}
}
|
abe8e369d0cee1cf85ddc2d864da875c6312d524
|
linux: environ is truncated for long environ
```
$ wc -c /proc/882252/environ
30417 /proc/882252/environ
```
environ for this process is truncated approximately half way through
|
0.26
| 887
|
suspicious size matching truncation: https://github.com/GuillaumeGomez/sysinfo/blob/master/src/linux/process.rs#L623
Nice catch! It should indeed add a size check when reading the file.
|
abe8e369d0cee1cf85ddc2d864da875c6312d524
|
[
"test_big_environ"
] |
[
"common::tests::check_display_impl_process_status",
"common::tests::check_uid_gid_from_impls",
"linux::network::test::refresh_networks_list_add_interface",
"system::tests::check_hostname_has_no_nuls",
"linux::network::test::refresh_networks_list_remove_interface",
"linux::system::test::lsb_release_fallback_not_android",
"system::tests::test_refresh_system",
"test::check_nb_supported_signals",
"test::check_memory_usage",
"test::check_cpus_number",
"test::ensure_is_supported_is_set_correctly",
"system::tests::test_refresh_process",
"test::check_host_name",
"test::check_system_info",
"test::check_cpu_usage",
"test::check_refresh_process_return_value",
"test::check_cmd_line",
"test::check_process_memory_usage",
"system::tests::check_if_send_and_sync",
"test::check_uid_gid",
"system::tests::test_get_process",
"test::check_refresh_process_update",
"test::check_cpu_frequency",
"test::check_users",
"test::check_processes_cpu_usage",
"system::tests::check_uptime",
"test_physical_core_numbers",
"test_cpu",
"test_disks",
"code_checkers::code_checks",
"test_networks",
"test_wait_child",
"test_process_refresh",
"test_process_session_id",
"test_process",
"cpu_usage_is_not_nan",
"test_process_disk_usage",
"test_cmd",
"test_process_times",
"test_environ",
"test_cwd",
"test_wait_non_child",
"test_refresh_process",
"test_refresh_processes",
"test_send_sync",
"test_uptime",
"src/common.rs - common::DiskType (line 504) - compile",
"src/common.rs - common::LoadAvg (line 643) - compile",
"src/common.rs - common::NetworksIter (line 467) - compile",
"src/common.rs - common::DiskUsage (line 805) - compile",
"src/common.rs - common::CpuRefreshKind::without_frequency (line 345)",
"src/common.rs - common::CpuRefreshKind::with_cpu_usage (line 344)",
"src/common.rs - common::PidExt::from_u32 (line 29)",
"src/common.rs - common::Pid (line 93)",
"src/common.rs - common::CpuRefreshKind::frequency (line 344)",
"src/common.rs - common::ProcessRefreshKind::everything (line 253)",
"src/common.rs - common::ProcessRefreshKind::with_disk_usage (line 272)",
"src/common.rs - common::RefreshKind::components (line 454)",
"src/common.rs - common::RefreshKind::components_list (line 455)",
"src/common.rs - common::CpuRefreshKind::with_frequency (line 345)",
"src/common.rs - common::RefreshKind::disks (line 450)",
"src/common.rs - common::CpuRefreshKind::everything (line 328)",
"src/common.rs - common::RefreshKind::cpu (line 454)",
"src/common.rs - common::PidExt::as_u32 (line 20)",
"src/common.rs - common::ProcessRefreshKind::new (line 239)",
"src/common.rs - common::CpuRefreshKind::without_cpu_usage (line 344)",
"src/common.rs - common::ProcessRefreshKind::with_user (line 278)",
"src/common.rs - common::CpuRefreshKind::new (line 315)",
"src/common.rs - common::RefreshKind::disks_list (line 451)",
"src/common.rs - common::CpuRefreshKind (line 292)",
"src/common.rs - common::PidExt (line 11)",
"src/common.rs - common::CpuRefreshKind::cpu_usage (line 343)",
"src/common.rs - common::ProcessRefreshKind::disk_usage (line 271)",
"src/common.rs - common::ProcessRefreshKind::without_disk_usage (line 272)",
"src/common.rs - common::ProcessRefreshKind::cpu (line 270)",
"src/common.rs - common::ProcessRefreshKind::with_cpu (line 271)",
"src/common.rs - common::ProcessRefreshKind::without_user (line 278)",
"src/common.rs - common::RefreshKind::everything (line 404)",
"src/common.rs - common::ProcessRefreshKind::without_cpu (line 271)",
"src/common.rs - common::User (line 769) - compile",
"src/common.rs - common::ProcessRefreshKind::user (line 279)",
"src/common.rs - common::get_current_pid (line 940) - compile",
"src/lib.rs - (line 127) - compile",
"src/lib.rs - (line 92) - compile",
"src/lib.rs - doctest::process_clone (line 141) - compile",
"src/common.rs - common::RefreshKind (line 352)",
"src/common.rs - common::ProcessRefreshKind (line 214)",
"src/lib.rs - doctest::process_clone (line 150) - compile fail",
"src/lib.rs - doctest::system_clone (line 163) - compile",
"src/lib.rs - doctest::system_clone (line 171) - compile fail",
"src/lib.rs - set_open_files_limit (line 95) - compile",
"src/linux/network.rs - linux::network::Networks (line 12) - compile",
"src/traits.rs - traits::ComponentExt::critical (line 1586) - compile",
"src/traits.rs - traits::ComponentExt::label (line 1602) - compile",
"src/traits.rs - traits::ComponentExt::max (line 1569) - compile",
"src/traits.rs - traits::ComponentExt::refresh (line 1627) - compile",
"src/traits.rs - traits::ComponentExt::temperature (line 1550) - compile",
"src/traits.rs - traits::CpuExt::cpu_usage (line 454) - compile",
"src/traits.rs - traits::CpuExt::brand (line 490) - compile",
"src/traits.rs - traits::CpuExt::frequency (line 502) - compile",
"src/traits.rs - traits::CpuExt::name (line 466) - compile",
"src/traits.rs - traits::CpuExt::vendor_id (line 478) - compile",
"src/traits.rs - traits::DiskExt (line 19) - compile",
"src/traits.rs - traits::DiskExt::available_space (line 90) - compile",
"src/traits.rs - traits::DiskExt::is_removable (line 102) - compile",
"src/traits.rs - traits::DiskExt::file_system (line 54) - compile",
"src/traits.rs - traits::DiskExt::refresh (line 114) - compile",
"src/traits.rs - traits::DiskExt::mount_point (line 66) - compile",
"src/traits.rs - traits::DiskExt::type_ (line 30) - compile",
"src/traits.rs - traits::DiskExt::name (line 42) - compile",
"src/common.rs - common::RefreshKind::networks_list (line 444)",
"src/common.rs - common::RefreshKind::with_networks_list (line 445)",
"src/traits.rs - traits::DiskExt::total_space (line 78) - compile",
"src/traits.rs - traits::NetworkExt::errors_on_transmitted (line 1483) - compile",
"src/traits.rs - traits::NetworkExt::errors_on_received (line 1457) - compile",
"src/common.rs - common::RefreshKind::new (line 382)",
"src/common.rs - common::RefreshKind::without_networks_list (line 445)",
"src/common.rs - common::RefreshKind::with_components (line 455)",
"src/traits.rs - traits::NetworkExt::packets_received (line 1405) - compile",
"src/traits.rs - traits::NetworkExt::received (line 1353) - compile",
"src/common.rs - common::RefreshKind::with_networks (line 444)",
"src/common.rs - common::RefreshKind::processes (line 437)",
"src/traits.rs - traits::NetworkExt::packets_transmitted (line 1431) - compile",
"src/traits.rs - traits::NetworkExt::total_errors_on_received (line 1470) - compile",
"src/common.rs - common::RefreshKind::memory (line 452)",
"src/common.rs - common::RefreshKind::users_list (line 461)",
"src/common.rs - common::RefreshKind::without_cpu (line 454)",
"src/common.rs - common::RefreshKind::with_components_list (line 456)",
"src/traits.rs - traits::NetworkExt::total_errors_on_transmitted (line 1496) - compile",
"src/common.rs - common::RefreshKind::networks (line 443)",
"src/traits.rs - traits::NetworkExt::transmitted (line 1379) - compile",
"src/traits.rs - traits::NetworkExt::total_packets_received (line 1418) - compile",
"src/traits.rs - traits::NetworkExt::total_packets_transmitted (line 1444) - compile",
"src/traits.rs - traits::NetworkExt::total_transmitted (line 1392) - compile",
"src/traits.rs - traits::NetworksExt::iter (line 1512) - compile",
"src/traits.rs - traits::NetworkExt::total_received (line 1366) - compile",
"src/common.rs - common::RefreshKind::with_memory (line 453)",
"src/common.rs - common::RefreshKind::without_components_list (line 456)",
"src/common.rs - common::RefreshKind::with_disks (line 451)",
"src/traits.rs - traits::NetworksExt::refresh (line 1536) - compile",
"src/common.rs - common::RefreshKind::with_disks_list (line 452)",
"src/traits.rs - traits::ProcessExt::cmd (line 191) - compile",
"src/traits.rs - traits::ProcessExt::cpu_usage (line 354) - compile",
"src/common.rs - common::RefreshKind::with_cpu (line 454)",
"src/traits.rs - traits::NetworksExt::refresh_networks_list (line 1525) - compile",
"src/common.rs - common::RefreshKind::with_users_list (line 462)",
"src/traits.rs - traits::ProcessExt::cwd (line 251) - compile",
"src/traits.rs - traits::ProcessExt::memory (line 275) - compile",
"src/traits.rs - traits::ProcessExt::run_time (line 335) - compile",
"src/traits.rs - traits::ProcessExt::group_id (line 405) - compile",
"src/traits.rs - traits::ProcessExt::pid (line 227) - compile",
"src/traits.rs - traits::ProcessExt::parent (line 299) - compile",
"src/traits.rs - traits::ProcessExt::kill_with (line 156) - compile",
"src/traits.rs - traits::ProcessExt::environ (line 239) - compile",
"src/traits.rs - traits::ProcessExt::exe (line 203) - compile",
"src/common.rs - common::RefreshKind::without_networks (line 444)",
"src/common.rs - common::RefreshKind::without_memory (line 453)",
"src/traits.rs - traits::ProcessExt::name (line 179) - compile",
"src/traits.rs - traits::ProcessExt::kill (line 135) - compile",
"src/traits.rs - traits::ProcessExt::status (line 311) - compile",
"src/traits.rs - traits::ProcessExt::disk_usage (line 368) - compile",
"src/traits.rs - traits::ProcessExt::root (line 263) - compile",
"src/traits.rs - traits::ProcessExt::user_id (line 390) - compile",
"src/common.rs - common::RefreshKind::without_disks_list (line 452)",
"src/traits.rs - traits::ProcessExt::start_time (line 323) - compile",
"src/traits.rs - traits::ProcessExt::session_id (line 435) - compile",
"src/traits.rs - traits::ProcessExt::virtual_memory (line 287) - compile",
"src/traits.rs - traits::SystemExt::available_memory (line 1058) - compile",
"src/common.rs - common::RefreshKind::without_disks (line 451)",
"src/traits.rs - traits::SystemExt::boot_time (line 1218) - compile",
"src/traits.rs - traits::ProcessExt::wait (line 418) - compile",
"src/traits.rs - traits::SystemExt::components (line 1108) - compile",
"src/traits.rs - traits::SystemExt::components_mut (line 1120) - compile",
"src/traits.rs - traits::SystemExt::global_cpu_info (line 983) - compile",
"src/traits.rs - traits::SystemExt::get_user_by_id (line 1333) - compile",
"src/traits.rs - traits::SystemExt::cpus (line 998) - compile",
"src/common.rs - common::RefreshKind::with_processes (line 437)",
"src/traits.rs - traits::SystemExt::free_memory (line 1042) - compile",
"src/traits.rs - traits::SystemExt::name (line 1246) - compile",
"src/traits.rs - traits::SystemExt::disks (line 1144) - compile",
"src/traits.rs - traits::SystemExt::kernel_version (line 1258) - compile",
"src/traits.rs - traits::SystemExt::load_average (line 1228) - compile",
"src/traits.rs - traits::SystemExt::networks (line 1179) - compile",
"src/traits.rs - traits::SystemExt::free_swap (line 1088) - compile",
"src/traits.rs - traits::SystemExt::host_name (line 1311) - compile",
"src/traits.rs - traits::SystemExt::long_os_version (line 1282) - compile",
"src/common.rs - common::RefreshKind::without_components (line 455)",
"src/traits.rs - traits::SystemExt::networks_mut (line 1197) - compile",
"src/traits.rs - traits::SystemExt::new_all (line 564) - compile",
"src/traits.rs - traits::SystemExt::new (line 549) - compile",
"src/traits.rs - traits::SystemExt::os_version (line 1270) - compile",
"src/traits.rs - traits::SystemExt::distribution_id (line 1299) - compile",
"src/traits.rs - traits::SystemExt::physical_core_count (line 1016) - compile",
"src/traits.rs - traits::SystemExt::disks_mut (line 1156) - compile",
"src/common.rs - common::RefreshKind::without_users_list (line 462)",
"src/traits.rs - traits::SystemExt::processes_by_name (line 927) - compile",
"src/traits.rs - traits::SystemExt::processes (line 894) - compile",
"src/traits.rs - traits::SystemExt::refresh_all (line 644) - compile",
"src/traits.rs - traits::SystemExt::processes_by_exact_name (line 958) - compile",
"src/traits.rs - traits::SystemExt::process (line 906) - compile",
"src/traits.rs - traits::SystemExt::refresh_components_list (line 736) - compile",
"src/traits.rs - traits::SystemExt::refresh_components (line 722) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks_list (line 829) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes (line 751) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 858) - compile",
"src/traits.rs - traits::SystemExt::refresh_cpu (line 697) - compile",
"src/traits.rs - traits::SystemExt::refresh_process (line 781) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks (line 805) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 881) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 849) - compile",
"src/traits.rs - traits::SystemExt::refresh_memory (line 680) - compile",
"src/traits.rs - traits::SystemExt::refresh_process_specifics (line 795) - compile",
"src/traits.rs - traits::SystemExt::refresh_cpu_specifics (line 712) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes_specifics (line 766) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 872) - compile",
"src/traits.rs - traits::SystemExt::refresh_users_list (line 839) - compile",
"src/traits.rs - traits::SystemExt::total_memory (line 1026) - compile",
"src/traits.rs - traits::SystemExt::total_swap (line 1078) - compile",
"src/traits.rs - traits::SystemExt::refresh_system (line 666) - compile",
"src/traits.rs - traits::SystemExt::uptime (line 1208) - compile",
"src/traits.rs - traits::UserExt (line 1642) - compile",
"src/traits.rs - traits::SystemExt::users (line 1132) - compile",
"src/traits.rs - traits::UserExt::groups (line 1694) - compile",
"src/traits.rs - traits::SystemExt::used_memory (line 1068) - compile",
"src/traits.rs - traits::UserExt::name (line 1682) - compile",
"src/traits.rs - traits::SystemExt::used_swap (line 1098) - compile",
"src/traits.rs - traits::UserExt::group_id (line 1670) - compile",
"src/traits.rs - traits::UserExt::id (line 1653) - compile",
"src/common.rs - common::RefreshKind::without_processes (line 437)",
"src/traits.rs - traits::SystemExt::IS_SUPPORTED (line 518)",
"src/lib.rs - (line 38)",
"src/traits.rs - traits::SystemExt::SUPPORTED_SIGNALS (line 532)",
"src/traits.rs - traits::SystemExt::new_with_specifics (line 578)",
"src/traits.rs - traits::SystemExt::refresh_specifics (line 599)"
] |
[] |
[] |
2022-09-03T12:49:44Z
|
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -469,4 +469,19 @@ mod test {
(new_total - total).abs()
);
}
+
+ // We ensure that the `Process` cmd information is retrieved as expected.
+ #[test]
+ fn check_cmd_line() {
+ if !System::IS_SUPPORTED {
+ return;
+ }
+ let mut sys = System::new();
+ sys.refresh_processes_specifics(ProcessRefreshKind::new());
+
+ assert!(sys
+ .processes()
+ .iter()
+ .any(|(_, process)| !process.cmd().is_empty()));
+ }
}
|
[
"833"
] |
GuillaumeGomez__sysinfo-835
|
GuillaumeGomez/sysinfo
|
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -353,6 +353,7 @@ fn retrieve_all_new_process_info(
if refresh_kind.user() {
refresh_user_group_ids(&mut p, &mut tmp);
+ tmp.pop();
}
if proc_list.pid.0 != 0 {
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -367,7 +368,6 @@ fn retrieve_all_new_process_info(
} else {
p.name = name.into();
- tmp.pop();
tmp.push("cmdline");
p.cmd = copy_from_file(&tmp);
diff --git a/src/linux/process.rs b/src/linux/process.rs
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -547,65 +547,65 @@ pub(crate) fn refresh_procs(
info: &SystemInfo,
refresh_kind: ProcessRefreshKind,
) -> bool {
- if let Ok(d) = fs::read_dir(path) {
- let folders = d
- .filter_map(|entry| {
- let entry = entry.ok()?;
- let entry = entry.path();
-
- if entry.is_dir() {
- Some(entry)
- } else {
- None
- }
+ let d = match fs::read_dir(path) {
+ Ok(d) => d,
+ Err(_) => return false,
+ };
+ let folders = d
+ .filter_map(|entry| {
+ let entry = entry.ok()?;
+ let entry = entry.path();
+
+ if entry.is_dir() {
+ Some(entry)
+ } else {
+ None
+ }
+ })
+ .collect::<Vec<_>>();
+ if pid.0 == 0 {
+ let proc_list = Wrap(UnsafeCell::new(proc_list));
+
+ #[cfg(feature = "multithread")]
+ use rayon::iter::ParallelIterator;
+
+ into_iter(folders)
+ .filter_map(|e| {
+ let (p, _) = _get_process_data(
+ e.as_path(),
+ proc_list.get(),
+ pid,
+ uptime,
+ info,
+ refresh_kind,
+ )
+ .ok()?;
+ p
})
- .collect::<Vec<_>>();
- if pid.0 == 0 {
- let proc_list = Wrap(UnsafeCell::new(proc_list));
-
- #[cfg(feature = "multithread")]
- use rayon::iter::ParallelIterator;
-
- into_iter(folders)
- .filter_map(|e| {
- let (p, _) = _get_process_data(
- e.as_path(),
- proc_list.get(),
- pid,
- uptime,
- info,
- refresh_kind,
- )
- .ok()?;
- p
- })
- .collect::<Vec<_>>()
- } else {
- let mut updated_pids = Vec::with_capacity(folders.len());
- let new_tasks = folders
- .iter()
- .filter_map(|e| {
- let (p, pid) =
- _get_process_data(e.as_path(), proc_list, pid, uptime, info, refresh_kind)
- .ok()?;
- updated_pids.push(pid);
- p
- })
- .collect::<Vec<_>>();
- // Sub-tasks are not cleaned up outside so we do it here directly.
- proc_list
- .tasks
- .retain(|&pid, _| updated_pids.iter().any(|&x| x == pid));
- new_tasks
- }
- .into_iter()
- .for_each(|e| {
- proc_list.tasks.insert(e.pid(), e);
- });
- true
+ .collect::<Vec<_>>()
} else {
- false
- }
+ let mut updated_pids = Vec::with_capacity(folders.len());
+ let new_tasks = folders
+ .iter()
+ .filter_map(|e| {
+ let (p, pid) =
+ _get_process_data(e.as_path(), proc_list, pid, uptime, info, refresh_kind)
+ .ok()?;
+ updated_pids.push(pid);
+ p
+ })
+ .collect::<Vec<_>>();
+ // Sub-tasks are not cleaned up outside so we do it here directly.
+ proc_list
+ .tasks
+ .retain(|&pid, _| updated_pids.iter().any(|&x| x == pid));
+ new_tasks
+ }
+ .into_iter()
+ .for_each(|e| {
+ proc_list.tasks.insert(e.pid(), e);
+ });
+ true
}
fn copy_from_file(entry: &Path) -> Vec<String> {
|
c7046eb4e189afcfb140057caa581d835e1cc51d
|
Obtaining linux command line requires ProcessRefreshKind::with_user() to be set
It seems retrieving process user information must be turned on when loading processes in linux for the command line to be retrieved.
### Expected
Refreshing a new System with ProcessRefreshKind::new() loads the process command line data as none of the ProcessRefreshKind options seem to pertain to it
### Actual
Refreshing a new System requires ProcessRefreshKind user retrieval to be turned on to obtain information about the process command line.
### Sample
```
// Does not include command line
let mut sys = System::new();
sys.refresh_processes_specifics(ProcessRefreshKind::new());
for (pid, process) in sys.processes() {
println!("A [{}] {} {:?}", pid, process.name(), process.cmd());
}
// Does not include command line
let mut sys = System::new();
sys.refresh_processes_specifics(ProcessRefreshKind::everything().without_user());
for (pid, process) in sys.processes() {
println!("B [{}] {} {:?}", pid, process.name(), process.cmd());
}
// Includes command line
let mut sys = System::new();
sys.refresh_processes_specifics(ProcessRefreshKind::new().with_user());
for (pid, process) in sys.processes() {
println!("C [{}] {} {:?}", pid, process.name(), process.cmd());
}
```
Version: 0.26.1
OS: RHEL8
|
0.26
| 835
|
This is intriguing. Thanks for opening this issue! I'll try to take a look in the next days but don't hesitate to check before if you want.
|
abe8e369d0cee1cf85ddc2d864da875c6312d524
|
[
"test::check_cmd_line"
] |
[
"common::tests::check_display_impl_process_status",
"system::tests::check_hostname_has_no_nuls",
"linux::network::test::refresh_networks_list_add_interface",
"linux::system::test::lsb_release_fallback_not_android",
"linux::network::test::refresh_networks_list_remove_interface",
"system::tests::test_refresh_system",
"test::check_nb_supported_signals",
"test::check_host_name",
"test::check_memory_usage",
"test::check_cpus_number",
"test::check_system_info",
"test::ensure_is_supported_is_set_correctly",
"system::tests::test_refresh_process",
"test::check_refresh_process_return_value",
"test::check_cpu_usage",
"test::check_process_memory_usage",
"system::tests::check_if_send_and_sync",
"test::check_uid_gid",
"system::tests::test_get_process",
"test::check_cpu_frequency",
"test::check_refresh_process_update",
"test::check_users",
"test::check_processes_cpu_usage",
"system::tests::check_uptime",
"test_physical_core_numbers",
"test_cpu",
"test_disks",
"code_checkers::code_checks",
"test_networks",
"test_process_refresh",
"test_process",
"cpu_usage_is_not_nan",
"test_process_disk_usage",
"test_cmd",
"test_environ",
"test_cwd",
"test_process_times",
"test_refresh_process",
"test_refresh_processes",
"test_send_sync",
"test_uptime",
"src/common.rs - common::DiskType (line 504) - compile",
"src/common.rs - common::DiskUsage (line 776) - compile",
"src/common.rs - common::NetworksIter (line 467) - compile",
"src/common.rs - common::LoadAvg (line 643) - compile",
"src/common.rs - common::ProcessRefreshKind::cpu (line 270)",
"src/common.rs - common::CpuRefreshKind::cpu_usage (line 343)",
"src/common.rs - common::CpuRefreshKind::everything (line 328)",
"src/common.rs - common::CpuRefreshKind (line 292)",
"src/common.rs - common::RefreshKind::components (line 454)",
"src/common.rs - common::CpuRefreshKind::without_cpu_usage (line 344)",
"src/common.rs - common::RefreshKind::cpu (line 454)",
"src/common.rs - common::ProcessRefreshKind::new (line 239)",
"src/common.rs - common::ProcessRefreshKind::with_cpu (line 271)",
"src/common.rs - common::CpuRefreshKind::with_frequency (line 345)",
"src/common.rs - common::RefreshKind::disks_list (line 451)",
"src/common.rs - common::CpuRefreshKind::with_cpu_usage (line 344)",
"src/common.rs - common::PidExt (line 11)",
"src/common.rs - common::ProcessRefreshKind::without_disk_usage (line 272)",
"src/common.rs - common::CpuRefreshKind::frequency (line 344)",
"src/common.rs - common::CpuRefreshKind::new (line 315)",
"src/common.rs - common::ProcessRefreshKind::with_user (line 278)",
"src/common.rs - common::Pid (line 93)",
"src/common.rs - common::ProcessRefreshKind::disk_usage (line 271)",
"src/common.rs - common::ProcessRefreshKind::user (line 279)",
"src/common.rs - common::PidExt::as_u32 (line 20)",
"src/common.rs - common::RefreshKind::everything (line 404)",
"src/common.rs - common::RefreshKind::disks (line 450)",
"src/common.rs - common::ProcessRefreshKind::without_user (line 278)",
"src/common.rs - common::ProcessRefreshKind::without_cpu (line 271)",
"src/common.rs - common::CpuRefreshKind::without_frequency (line 345)",
"src/common.rs - common::RefreshKind::components_list (line 455)",
"src/common.rs - common::RefreshKind (line 352)",
"src/common.rs - common::ProcessRefreshKind::with_disk_usage (line 272)",
"src/common.rs - common::ProcessRefreshKind::everything (line 253)",
"src/common.rs - common::get_current_pid (line 911) - compile",
"src/common.rs - common::PidExt::from_u32 (line 29)",
"src/common.rs - common::User (line 740) - compile",
"src/lib.rs - doctest::process_clone (line 149) - compile fail",
"src/lib.rs - doctest::system_clone (line 162) - compile",
"src/lib.rs - doctest::process_clone (line 140) - compile",
"src/lib.rs - doctest::system_clone (line 170) - compile fail",
"src/common.rs - common::ProcessRefreshKind (line 214)",
"src/lib.rs - set_open_files_limit (line 94) - compile",
"src/traits.rs - traits::ComponentExt::critical (line 1517) - compile",
"src/linux/network.rs - linux::network::Networks (line 12) - compile",
"src/traits.rs - traits::ComponentExt::label (line 1533) - compile",
"src/traits.rs - traits::ComponentExt::max (line 1500) - compile",
"src/traits.rs - traits::ComponentExt::refresh (line 1558) - compile",
"src/traits.rs - traits::ComponentExt::temperature (line 1481) - compile",
"src/traits.rs - traits::CpuExt::brand (line 460) - compile",
"src/common.rs - common::RefreshKind::memory (line 452)",
"src/traits.rs - traits::CpuExt::cpu_usage (line 424) - compile",
"src/traits.rs - traits::CpuExt::frequency (line 472) - compile",
"src/traits.rs - traits::CpuExt::name (line 436) - compile",
"src/traits.rs - traits::CpuExt::vendor_id (line 448) - compile",
"src/traits.rs - traits::DiskExt (line 19) - compile",
"src/traits.rs - traits::DiskExt::available_space (line 90) - compile",
"src/common.rs - common::RefreshKind::processes (line 437)",
"src/common.rs - common::RefreshKind::networks (line 443)",
"src/common.rs - common::RefreshKind::with_cpu (line 454)",
"src/common.rs - common::RefreshKind::users_list (line 461)",
"src/common.rs - common::RefreshKind::with_users_list (line 462)",
"src/common.rs - common::RefreshKind::networks_list (line 444)",
"src/common.rs - common::RefreshKind::new (line 382)",
"src/common.rs - common::RefreshKind::with_disks_list (line 452)",
"src/traits.rs - traits::NetworkExt::errors_on_received (line 1388) - compile",
"src/traits.rs - traits::DiskExt::file_system (line 54) - compile",
"src/common.rs - common::RefreshKind::with_networks (line 444)",
"src/traits.rs - traits::NetworkExt::errors_on_transmitted (line 1414) - compile",
"src/traits.rs - traits::NetworkExt::packets_received (line 1336) - compile",
"src/common.rs - common::RefreshKind::with_disks (line 451)",
"src/common.rs - common::RefreshKind::without_components (line 455)",
"src/common.rs - common::RefreshKind::with_components (line 455)",
"src/traits.rs - traits::DiskExt::mount_point (line 66) - compile",
"src/traits.rs - traits::DiskExt::is_removable (line 102) - compile",
"src/traits.rs - traits::NetworkExt::packets_transmitted (line 1362) - compile",
"src/traits.rs - traits::NetworkExt::received (line 1284) - compile",
"src/traits.rs - traits::DiskExt::name (line 42) - compile",
"src/traits.rs - traits::DiskExt::refresh (line 114) - compile",
"src/traits.rs - traits::NetworkExt::total_errors_on_transmitted (line 1427) - compile",
"src/traits.rs - traits::NetworkExt::total_errors_on_received (line 1401) - compile",
"src/common.rs - common::RefreshKind::with_components_list (line 456)",
"src/traits.rs - traits::NetworkExt::total_received (line 1297) - compile",
"src/traits.rs - traits::DiskExt::type_ (line 30) - compile",
"src/traits.rs - traits::NetworkExt::total_packets_transmitted (line 1375) - compile",
"src/common.rs - common::RefreshKind::with_memory (line 453)",
"src/traits.rs - traits::DiskExt::total_space (line 78) - compile",
"src/traits.rs - traits::NetworkExt::total_packets_received (line 1349) - compile",
"src/common.rs - common::RefreshKind::with_processes (line 437)",
"src/traits.rs - traits::ProcessExt::cmd (line 191) - compile",
"src/traits.rs - traits::NetworkExt::transmitted (line 1310) - compile",
"src/traits.rs - traits::NetworkExt::total_transmitted (line 1323) - compile",
"src/traits.rs - traits::NetworksExt::refresh_networks_list (line 1456) - compile",
"src/traits.rs - traits::ProcessExt::cpu_usage (line 354) - compile",
"src/common.rs - common::RefreshKind::without_cpu (line 454)",
"src/common.rs - common::RefreshKind::without_components_list (line 456)",
"src/traits.rs - traits::NetworksExt::iter (line 1443) - compile",
"src/traits.rs - traits::ProcessExt::cwd (line 251) - compile",
"src/traits.rs - traits::ProcessExt::exe (line 203) - compile",
"src/traits.rs - traits::ProcessExt::disk_usage (line 368) - compile",
"src/traits.rs - traits::NetworksExt::refresh (line 1467) - compile",
"src/common.rs - common::RefreshKind::with_networks_list (line 445)",
"src/traits.rs - traits::ProcessExt::group_id (line 405) - compile",
"src/traits.rs - traits::ProcessExt::environ (line 239) - compile",
"src/traits.rs - traits::ProcessExt::parent (line 299) - compile",
"src/traits.rs - traits::ProcessExt::root (line 263) - compile",
"src/traits.rs - traits::ProcessExt::name (line 179) - compile",
"src/traits.rs - traits::ProcessExt::run_time (line 335) - compile",
"src/traits.rs - traits::ProcessExt::kill (line 135) - compile",
"src/traits.rs - traits::ProcessExt::pid (line 227) - compile",
"src/common.rs - common::RefreshKind::without_disks_list (line 452)",
"src/traits.rs - traits::ProcessExt::user_id (line 390) - compile",
"src/traits.rs - traits::ProcessExt::status (line 311) - compile",
"src/traits.rs - traits::ProcessExt::memory (line 275) - compile",
"src/traits.rs - traits::ProcessExt::kill_with (line 156) - compile",
"src/traits.rs - traits::ProcessExt::virtual_memory (line 287) - compile",
"src/common.rs - common::RefreshKind::without_networks_list (line 445)",
"src/common.rs - common::RefreshKind::without_memory (line 453)",
"src/traits.rs - traits::SystemExt::available_memory (line 1006) - compile",
"src/traits.rs - traits::SystemExt::boot_time (line 1166) - compile",
"src/traits.rs - traits::ProcessExt::start_time (line 323) - compile",
"src/traits.rs - traits::SystemExt::free_memory (line 990) - compile",
"src/traits.rs - traits::SystemExt::components (line 1056) - compile",
"src/traits.rs - traits::SystemExt::disks_mut (line 1104) - compile",
"src/traits.rs - traits::SystemExt::free_swap (line 1036) - compile",
"src/traits.rs - traits::SystemExt::disks (line 1092) - compile",
"src/traits.rs - traits::SystemExt::get_user_by_id (line 1264) - compile",
"src/traits.rs - traits::SystemExt::load_average (line 1176) - compile",
"src/traits.rs - traits::SystemExt::cpus (line 946) - compile",
"src/traits.rs - traits::SystemExt::global_cpu_info (line 931) - compile",
"src/traits.rs - traits::SystemExt::kernel_version (line 1206) - compile",
"src/traits.rs - traits::SystemExt::components_mut (line 1068) - compile",
"src/traits.rs - traits::SystemExt::host_name (line 1242) - compile",
"src/traits.rs - traits::SystemExt::physical_core_count (line 964) - compile",
"src/traits.rs - traits::SystemExt::name (line 1194) - compile",
"src/traits.rs - traits::SystemExt::processes (line 854) - compile",
"src/traits.rs - traits::SystemExt::long_os_version (line 1230) - compile",
"src/traits.rs - traits::SystemExt::new_all (line 534) - compile",
"src/traits.rs - traits::SystemExt::new (line 519) - compile",
"src/traits.rs - traits::SystemExt::os_version (line 1218) - compile",
"src/traits.rs - traits::SystemExt::process (line 866) - compile",
"src/traits.rs - traits::SystemExt::processes_by_name (line 881) - compile",
"src/traits.rs - traits::SystemExt::refresh_all (line 614) - compile",
"src/traits.rs - traits::SystemExt::networks_mut (line 1145) - compile",
"src/traits.rs - traits::SystemExt::processes_by_exact_name (line 906) - compile",
"src/traits.rs - traits::SystemExt::networks (line 1127) - compile",
"src/common.rs - common::RefreshKind::without_networks (line 444)",
"src/common.rs - common::RefreshKind::without_disks (line 451)",
"src/common.rs - common::RefreshKind::without_processes (line 437)",
"src/traits.rs - traits::SystemExt::refresh_components (line 692) - compile",
"src/traits.rs - traits::SystemExt::refresh_memory (line 650) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 809) - compile",
"src/traits.rs - traits::SystemExt::refresh_components_list (line 706) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks_list (line 789) - compile",
"src/traits.rs - traits::SystemExt::refresh_cpu_specifics (line 682) - compile",
"src/traits.rs - traits::SystemExt::refresh_cpu (line 667) - compile",
"src/traits.rs - traits::SystemExt::refresh_process (line 751) - compile",
"src/traits.rs - traits::SystemExt::used_swap (line 1046) - compile",
"src/traits.rs - traits::SystemExt::refresh_users_list (line 799) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes (line 721) - compile",
"src/traits.rs - traits::SystemExt::refresh_disks (line 775) - compile",
"src/traits.rs - traits::SystemExt::used_memory (line 1016) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks (line 818) - compile",
"src/traits.rs - traits::SystemExt::refresh_process_specifics (line 765) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 832) - compile",
"src/traits.rs - traits::SystemExt::refresh_networks_list (line 841) - compile",
"src/traits.rs - traits::SystemExt::total_swap (line 1026) - compile",
"src/traits.rs - traits::SystemExt::refresh_system (line 636) - compile",
"src/traits.rs - traits::SystemExt::uptime (line 1156) - compile",
"src/traits.rs - traits::SystemExt::total_memory (line 974) - compile",
"src/traits.rs - traits::UserExt (line 1573) - compile",
"src/traits.rs - traits::SystemExt::users (line 1080) - compile",
"src/traits.rs - traits::SystemExt::refresh_processes_specifics (line 736) - compile",
"src/traits.rs - traits::UserExt::groups (line 1625) - compile",
"src/traits.rs - traits::UserExt::group_id (line 1601) - compile",
"src/traits.rs - traits::UserExt::id (line 1584) - compile",
"src/common.rs - common::RefreshKind::without_users_list (line 462)",
"src/traits.rs - traits::UserExt::name (line 1613) - compile",
"src/traits.rs - traits::SystemExt::IS_SUPPORTED (line 488)",
"src/lib.rs - (line 38)",
"src/traits.rs - traits::SystemExt::SUPPORTED_SIGNALS (line 502)",
"src/traits.rs - traits::SystemExt::new_with_specifics (line 548)",
"src/traits.rs - traits::SystemExt::refresh_specifics (line 569)"
] |
[] |
[] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.