-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsystem.rs
More file actions
2760 lines (2580 loc) · 82.3 KB
/
system.rs
File metadata and controls
2760 lines (2580 loc) · 82.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Take a look at the license at the top of the repository in the LICENSE file.
use std::collections::{HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::path::Path;
use std::str::FromStr;
use crate::{CpuInner, Gid, ProcessInner, SystemInner, Uid};
/// Structs containing system's information such as processes, memory and CPU.
///
/// ```
/// use sysinfo::System;
///
/// if sysinfo::IS_SUPPORTED_SYSTEM {
/// println!("System: {:?}", System::new_all());
/// } else {
/// println!("This OS isn't supported (yet?).");
/// }
/// ```
pub struct System {
pub(crate) inner: SystemInner,
}
impl Default for System {
fn default() -> System {
System::new()
}
}
impl System {
/// Creates a new [`System`] instance with nothing loaded.
///
/// Use one of the refresh methods (like [`refresh_all`]) to update its internal information.
///
/// [`System`]: crate::System
/// [`refresh_all`]: #method.refresh_all
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new();
/// ```
pub fn new() -> Self {
Self::new_with_specifics(RefreshKind::new())
}
/// Creates a new [`System`] instance with everything loaded.
///
/// It is an equivalent of [`System::new_with_specifics`]`(`[`RefreshKind::everything`]`())`.
///
/// [`System`]: crate::System
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// ```
pub fn new_all() -> Self {
Self::new_with_specifics(RefreshKind::everything())
}
/// Creates a new [`System`] instance and refresh the data corresponding to the
/// given [`RefreshKind`].
///
/// [`System`]: crate::System
///
/// ```
/// use sysinfo::{ProcessRefreshKind, RefreshKind, System};
///
/// // We want to only refresh processes.
/// let mut system = System::new_with_specifics(
/// RefreshKind::new().with_processes(ProcessRefreshKind::everything()),
/// );
///
/// # if sysinfo::IS_SUPPORTED_SYSTEM && !cfg!(feature = "apple-sandbox") {
/// assert!(!system.processes().is_empty());
/// # }
/// ```
pub fn new_with_specifics(refreshes: RefreshKind) -> Self {
let mut s = Self {
inner: SystemInner::new(),
};
s.refresh_specifics(refreshes);
s
}
/// Refreshes according to the given [`RefreshKind`]. It calls the corresponding
/// "refresh_" methods.
///
/// ```
/// use sysinfo::{ProcessRefreshKind, RefreshKind, System};
///
/// let mut s = System::new_all();
///
/// // Let's just update processes:
/// s.refresh_specifics(
/// RefreshKind::new().with_processes(ProcessRefreshKind::everything()),
/// );
/// ```
pub fn refresh_specifics(&mut self, refreshes: RefreshKind) {
if let Some(kind) = refreshes.memory() {
self.refresh_memory_specifics(kind);
}
if let Some(kind) = refreshes.cpu() {
self.refresh_cpu_specifics(kind);
}
if let Some(kind) = refreshes.processes() {
// =====================================================================================
// FIXME: Sysinfo code in EDGELESS (which runs inside a container) has some problems (see SecureExecutor sysinfo behaviour).
// The following code is a workaround, which updates information
// with the help of a separate program that runs outside of the enclave, in the untrusted world.
crate::unix::linux::process::update_processes_from_untrusted_part_edgeless_workaround(self.inner.processes_mut());
// Original sysinfo code
self.refresh_processes_specifics(ProcessesToUpdate::All, false, kind);
}
}
/// Refreshes all system and processes information.
///
/// It is the same as calling `system.refresh_specifics(RefreshKind::everything())`.
///
/// Don't forget to take a look at [`ProcessRefreshKind::everything`] method to see what it
/// will update for processes more in details.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new();
/// s.refresh_all();
/// ```
pub fn refresh_all(&mut self) {
self.refresh_specifics(RefreshKind::everything());
}
/// Refreshes RAM and SWAP usage.
///
/// It is the same as calling `system.refresh_memory_specifics(MemoryRefreshKind::everything())`.
///
/// If you don't want to refresh both, take a look at [`System::refresh_memory_specifics`].
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new();
/// s.refresh_memory();
/// ```
pub fn refresh_memory(&mut self) {
self.refresh_memory_specifics(MemoryRefreshKind::everything())
}
/// Refreshes system memory specific information.
///
/// ```no_run
/// use sysinfo::{MemoryRefreshKind, System};
///
/// let mut s = System::new();
/// s.refresh_memory_specifics(MemoryRefreshKind::new().with_ram());
/// ```
pub fn refresh_memory_specifics(&mut self, refresh_kind: MemoryRefreshKind) {
self.inner.refresh_memory_specifics(refresh_kind)
}
/// Refreshes CPUs usage.
///
/// ⚠️ Please note that the result will very likely be inaccurate at the first call.
/// You need to call this method at least twice (with a bit of time between each call, like
/// 200 ms, take a look at [`MINIMUM_CPU_UPDATE_INTERVAL`] for more information)
/// to get accurate value as it uses previous results to compute the next value.
///
/// Calling this method is the same as calling
/// `system.refresh_cpu_specifics(CpuRefreshKind::new().with_cpu_usage())`.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new_all();
/// // Wait a bit because CPU usage is based on diff.
/// std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
/// // Refresh CPUs again.
/// s.refresh_cpu_usage();
/// ```
///
/// [`MINIMUM_CPU_UPDATE_INTERVAL`]: crate::MINIMUM_CPU_UPDATE_INTERVAL
pub fn refresh_cpu_usage(&mut self) {
self.refresh_cpu_specifics(CpuRefreshKind::new().with_cpu_usage())
}
/// Refreshes CPUs frequency information.
///
/// Calling this method is the same as calling
/// `system.refresh_cpu_specifics(CpuRefreshKind::new().with_frequency())`.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new_all();
/// s.refresh_cpu_frequency();
/// ```
pub fn refresh_cpu_frequency(&mut self) {
self.refresh_cpu_specifics(CpuRefreshKind::new().with_frequency())
}
/// Refreshes the list of CPU.
///
/// Normally, this should almost never be needed as it's pretty rare for a computer
/// to add a CPU while running, but it's possible on some computers which shutdown
/// CPU if the load is low enough.
///
/// The `refresh_kind` argument tells what information you want to be retrieved
/// for each CPU.
///
/// ```no_run
/// use sysinfo::{CpuRefreshKind, System};
///
/// let mut s = System::new_all();
/// // We already have the list of CPU filled, but we want to recompute it
/// // in case new CPUs were added.
/// s.refresh_cpu_list(CpuRefreshKind::everything());
/// ```
pub fn refresh_cpu_list(&mut self, refresh_kind: CpuRefreshKind) {
self.inner.refresh_cpu_list(refresh_kind);
}
/// Refreshes all information related to CPUs information.
///
/// If you only want the CPU usage, use [`System::refresh_cpu_usage`] instead.
///
/// ⚠️ Please note that the result will be inaccurate at the first call.
/// You need to call this method at least twice (with a bit of time between each call, like
/// 200 ms, take a look at [`MINIMUM_CPU_UPDATE_INTERVAL`] for more information)
/// to get accurate value as it uses previous results to compute the next value.
///
/// Calling this method is the same as calling
/// `system.refresh_cpu_specifics(CpuRefreshKind::everything())`.
///
/// ```no_run
/// use sysinfo::System;
///
/// let mut s = System::new_all();
/// s.refresh_cpu_all();
/// ```
///
/// [`MINIMUM_CPU_UPDATE_INTERVAL`]: crate::MINIMUM_CPU_UPDATE_INTERVAL
pub fn refresh_cpu_all(&mut self) {
self.refresh_cpu_specifics(CpuRefreshKind::everything())
}
/// Refreshes CPUs specific information.
///
/// ```no_run
/// use sysinfo::{System, CpuRefreshKind};
///
/// let mut s = System::new_all();
/// s.refresh_cpu_specifics(CpuRefreshKind::everything());
/// ```
pub fn refresh_cpu_specifics(&mut self, refresh_kind: CpuRefreshKind) {
self.inner.refresh_cpu_specifics(refresh_kind)
}
/// Gets all processes and updates their information.
///
/// It does the same as:
///
/// ```no_run
/// # use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System, UpdateKind};
/// # let mut system = System::new();
/// system.refresh_processes_specifics(
/// ProcessesToUpdate::All,
/// true,
/// ProcessRefreshKind::new()
/// .with_memory()
/// .with_cpu()
/// .with_disk_usage()
/// .with_exe(UpdateKind::OnlyIfNotSet),
/// );
/// ```
///
/// ⚠️ `remove_dead_processes` works as follows: if an updated process is dead, then it is
/// removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed
/// since 7 is not part of the update.
///
/// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour
/// by using [`set_open_files_limit`][crate::set_open_files_limit].
///
/// Example:
///
/// ```no_run
/// use sysinfo::{ProcessesToUpdate, System};
///
/// let mut s = System::new_all();
/// s.refresh_processes(ProcessesToUpdate::All, true);
/// ```
pub fn refresh_processes(
&mut self,
processes_to_update: ProcessesToUpdate<'_>,
remove_dead_processes: bool,
) -> usize {
self.refresh_processes_specifics(
processes_to_update,
remove_dead_processes,
ProcessRefreshKind::new()
.with_memory()
.with_cpu()
.with_disk_usage()
.with_exe(UpdateKind::OnlyIfNotSet),
)
}
/// Gets all processes and updates the specified information.
///
/// Returns the number of updated processes.
///
/// ⚠️ `remove_dead_processes` works as follows: if an updated process is dead, then it is
/// removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed
/// since 7 is not part of the update.
///
/// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour
/// by using [`set_open_files_limit`][crate::set_open_files_limit].
///
/// ```no_run
/// use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System};
///
/// let mut s = System::new_all();
/// s.refresh_processes_specifics(
/// ProcessesToUpdate::All,
/// true,
/// ProcessRefreshKind::everything(),
/// );
/// ```
pub fn refresh_processes_specifics(
&mut self,
processes_to_update: ProcessesToUpdate<'_>,
remove_dead_processes: bool,
refresh_kind: ProcessRefreshKind,
) -> usize {
fn update_and_remove(pid: &Pid, processes: &mut HashMap<Pid, Process>) {
let updated = if let Some(proc) = processes.get_mut(pid) {
proc.inner.switch_updated()
} else {
return;
};
if !updated {
processes.remove(pid);
}
}
fn update(pid: &Pid, processes: &mut HashMap<Pid, Process>) {
if let Some(proc) = processes.get_mut(pid) {
proc.inner.switch_updated();
}
}
let nb_updated = self
.inner
.refresh_processes_specifics(processes_to_update, refresh_kind);
let processes = self.inner.processes_mut();
match processes_to_update {
ProcessesToUpdate::All => {
if remove_dead_processes {
processes.retain(|_, v| v.inner.switch_updated());
} else {
for proc in processes.values_mut() {
proc.inner.switch_updated();
}
}
}
ProcessesToUpdate::Some(pids) => {
let call = if remove_dead_processes {
update_and_remove
} else {
update
};
for pid in pids {
call(pid, processes);
}
}
}
nb_updated
}
/// Returns the process list.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// for (pid, process) in s.processes() {
/// println!("{} {:?}", pid, process.name());
/// }
/// ```
pub fn processes(&self) -> &HashMap<Pid, Process> {
self.inner.processes()
}
/// Returns the process corresponding to the given `pid` or `None` if no such process exists.
///
/// ```no_run
/// use sysinfo::{Pid, System};
///
/// let s = System::new_all();
/// if let Some(process) = s.process(Pid::from(1337)) {
/// println!("{:?}", process.name());
/// }
/// ```
pub fn process(&self, pid: Pid) -> Option<&Process> {
self.inner.process(pid)
}
/// Returns an iterator of process containing the given `name`.
///
/// If you want only the processes with exactly the given `name`, take a look at
/// [`System::processes_by_exact_name`].
///
/// **⚠️ Important ⚠️**
///
/// On **Linux**, there are two things to know about processes' name:
/// 1. It is limited to 15 characters.
/// 2. It is not always the exe name.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// for process in s.processes_by_name("htop".as_ref()) {
/// println!("{} {:?}", process.pid(), process.name());
/// }
/// ```
pub fn processes_by_name<'a: 'b, 'b>(
&'a self,
name: &'b OsStr,
) -> impl Iterator<Item = &'a Process> + 'b {
let finder = memchr::memmem::Finder::new(name.as_encoded_bytes());
self.processes()
.values()
.filter(move |val: &&Process| finder.find(val.name().as_encoded_bytes()).is_some())
}
/// Returns an iterator of processes with exactly the given `name`.
///
/// If you instead want the processes containing `name`, take a look at
/// [`System::processes_by_name`].
///
/// **⚠️ Important ⚠️**
///
/// On **Linux**, there are two things to know about processes' name:
/// 1. It is limited to 15 characters.
/// 2. It is not always the exe name.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// for process in s.processes_by_exact_name("htop".as_ref()) {
/// println!("{} {:?}", process.pid(), process.name());
/// }
/// ```
pub fn processes_by_exact_name<'a: 'b, 'b>(
&'a self,
name: &'b OsStr,
) -> impl Iterator<Item = &'a Process> + 'b {
self.processes()
.values()
.filter(move |val: &&Process| val.name() == name)
}
/// Returns "global" CPUs usage (aka the addition of all the CPUs).
///
/// To have up-to-date information, you need to call [`System::refresh_cpu_specifics`] or
/// [`System::refresh_specifics`] with `cpu` enabled.
///
/// ```no_run
/// use sysinfo::{CpuRefreshKind, RefreshKind, System};
///
/// let mut s = System::new_with_specifics(
/// RefreshKind::new().with_cpu(CpuRefreshKind::everything()),
/// );
/// // Wait a bit because CPU usage is based on diff.
/// std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
/// // Refresh CPUs again to get actual value.
/// s.refresh_cpu_usage();
/// println!("{}%", s.global_cpu_usage());
/// ```
pub fn global_cpu_usage(&self) -> f32 {
self.inner.global_cpu_usage()
}
/// Returns the list of the CPUs.
///
/// By default, the list of CPUs is empty until you call [`System::refresh_cpu_specifics`] or
/// [`System::refresh_specifics`] with `cpu` enabled.
///
/// ```no_run
/// use sysinfo::{CpuRefreshKind, RefreshKind, System};
///
/// let mut s = System::new_with_specifics(
/// RefreshKind::new().with_cpu(CpuRefreshKind::everything()),
/// );
/// // Wait a bit because CPU usage is based on diff.
/// std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
/// // Refresh CPUs again to get actual value.
/// s.refresh_cpu_usage();
/// for cpu in s.cpus() {
/// println!("{}%", cpu.cpu_usage());
/// }
/// ```
pub fn cpus(&self) -> &[Cpu] {
self.inner.cpus()
}
/// Returns the number of physical cores on the CPU or `None` if it couldn't get it.
///
/// In case there are multiple CPUs, it will combine the physical core count of all the CPUs.
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new();
/// println!("{:?}", s.physical_core_count());
/// ```
pub fn physical_core_count(&self) -> Option<usize> {
self.inner.physical_core_count()
}
/// Returns the RAM size in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.total_memory());
/// ```
///
/// On Linux, if you want to see this information with the limit of your cgroup, take a look
/// at [`cgroup_limits`](System::cgroup_limits).
pub fn total_memory(&self) -> u64 {
self.inner.total_memory()
}
/// Returns the amount of free RAM in bytes.
///
/// Generally, "free" memory refers to unallocated memory whereas "available" memory refers to
/// memory that is available for (re)use.
///
/// Side note: Windows doesn't report "free" memory so this method returns the same value
/// as [`available_memory`](System::available_memory).
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.free_memory());
/// ```
pub fn free_memory(&self) -> u64 {
self.inner.free_memory()
}
/// Returns the amount of available RAM in bytes.
///
/// Generally, "free" memory refers to unallocated memory whereas "available" memory refers to
/// memory that is available for (re)use.
///
/// ⚠️ Windows and FreeBSD don't report "available" memory so [`System::free_memory`]
/// returns the same value as this method.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.available_memory());
/// ```
pub fn available_memory(&self) -> u64 {
self.inner.available_memory()
}
/// Returns the amount of used RAM in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.used_memory());
/// ```
pub fn used_memory(&self) -> u64 {
self.inner.used_memory()
}
/// Returns the SWAP size in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.total_swap());
/// ```
pub fn total_swap(&self) -> u64 {
self.inner.total_swap()
}
/// Returns the amount of free SWAP in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.free_swap());
/// ```
pub fn free_swap(&self) -> u64 {
self.inner.free_swap()
}
/// Returns the amount of used SWAP in bytes.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("{} bytes", s.used_swap());
/// ```
pub fn used_swap(&self) -> u64 {
self.inner.used_swap()
}
/// Retrieves the limits for the current cgroup (if any), otherwise it returns `None`.
///
/// This information is computed every time the method is called.
///
/// ⚠️ You need to have run [`refresh_memory`](System::refresh_memory) at least once before
/// calling this method.
///
/// ⚠️ This method is only implemented for Linux. It always returns `None` for all other
/// systems.
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// println!("limits: {:?}", s.cgroup_limits());
/// ```
pub fn cgroup_limits(&self) -> Option<CGroupLimits> {
self.inner.cgroup_limits()
}
/// Returns system uptime (in seconds).
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("System running since {} seconds", System::uptime());
/// ```
pub fn uptime() -> u64 {
SystemInner::uptime()
}
/// Returns the time (in seconds) when the system booted since UNIX epoch.
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("System booted at {} seconds", System::boot_time());
/// ```
pub fn boot_time() -> u64 {
SystemInner::boot_time()
}
/// Returns the system load average value.
///
/// **Important**: this information is computed every time this function is called.
///
/// ⚠️ This is currently not working on **Windows**.
///
/// ```no_run
/// use sysinfo::System;
///
/// let load_avg = System::load_average();
/// println!(
/// "one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
/// load_avg.one,
/// load_avg.five,
/// load_avg.fifteen,
/// );
/// ```
pub fn load_average() -> LoadAvg {
SystemInner::load_average()
}
/// Returns the system name.
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("OS: {:?}", System::name());
/// ```
pub fn name() -> Option<String> {
SystemInner::name()
}
/// Returns the system's kernel version.
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("kernel version: {:?}", System::kernel_version());
/// ```
pub fn kernel_version() -> Option<String> {
SystemInner::kernel_version()
}
/// Returns the system version (e.g. for MacOS this will return 11.1 rather than the kernel
/// version).
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("OS version: {:?}", System::os_version());
/// ```
pub fn os_version() -> Option<String> {
SystemInner::os_version()
}
/// Returns the system long os version (e.g "MacOS 11.2 BigSur").
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("Long OS Version: {:?}", System::long_os_version());
/// ```
pub fn long_os_version() -> Option<String> {
SystemInner::long_os_version()
}
/// Returns the distribution id as defined by os-release,
/// or [`std::env::consts::OS`].
///
/// See also
/// - <https://www.freedesktop.org/software/systemd/man/os-release.html#ID=>
/// - <https://doc.rust-lang.org/std/env/consts/constant.OS.html>
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("Distribution ID: {:?}", System::distribution_id());
/// ```
pub fn distribution_id() -> String {
SystemInner::distribution_id()
}
/// Returns the system hostname based off DNS.
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("Hostname: {:?}", System::host_name());
/// ```
pub fn host_name() -> Option<String> {
SystemInner::host_name()
}
/// Returns the CPU architecture (eg. x86, amd64, aarch64, ...).
///
/// **Important**: this information is computed every time this function is called.
///
/// ```no_run
/// use sysinfo::System;
///
/// println!("CPU Architecture: {:?}", System::cpu_arch());
/// ```
pub fn cpu_arch() -> String {
SystemInner::cpu_arch().unwrap_or_else(|| std::env::consts::ARCH.to_owned())
}
}
/// A struct representing system load average value.
///
/// It is returned by [`System::load_average`][crate::System::load_average].
///
/// ```no_run
/// use sysinfo::System;
///
/// let load_avg = System::load_average();
/// println!(
/// "one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
/// load_avg.one,
/// load_avg.five,
/// load_avg.fifteen,
/// );
/// ```
#[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,
}
/// An enum representing signals on UNIX-like systems.
///
/// On non-unix systems, this enum is mostly useless and is only there to keep coherency between
/// the different OSes.
///
/// If you want the list of the supported signals on the current system, use
/// [`SUPPORTED_SIGNALS`][crate::SUPPORTED_SIGNALS].
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Debug)]
pub enum Signal {
/// Hangup detected on controlling terminal or death of controlling process.
Hangup,
/// Interrupt from keyboard.
Interrupt,
/// Quit from keyboard.
Quit,
/// Illegal instruction.
Illegal,
/// Trace/breakpoint trap.
Trap,
/// Abort signal from C abort function.
Abort,
/// IOT trap. A synonym for SIGABRT.
IOT,
/// Bus error (bad memory access).
Bus,
/// Floating point exception.
FloatingPointException,
/// Kill signal.
Kill,
/// User-defined signal 1.
User1,
/// Invalid memory reference.
Segv,
/// User-defined signal 2.
User2,
/// Broken pipe: write to pipe with no readers.
Pipe,
/// Timer signal from C alarm function.
Alarm,
/// Termination signal.
Term,
/// Child stopped or terminated.
Child,
/// Continue if stopped.
Continue,
/// Stop process.
Stop,
/// Stop typed at terminal.
TSTP,
/// Terminal input for background process.
TTIN,
/// Terminal output for background process.
TTOU,
/// Urgent condition on socket.
Urgent,
/// CPU time limit exceeded.
XCPU,
/// File size limit exceeded.
XFSZ,
/// Virtual alarm clock.
VirtualAlarm,
/// Profiling time expired.
Profiling,
/// Windows resize signal.
Winch,
/// I/O now possible.
IO,
/// Pollable event (Sys V). Synonym for IO
Poll,
/// Power failure (System V).
///
/// Doesn't exist on apple systems so will be ignored.
Power,
/// Bad argument to routine (SVr4).
Sys,
}
impl std::fmt::Display for Signal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match *self {
Self::Hangup => "Hangup",
Self::Interrupt => "Interrupt",
Self::Quit => "Quit",
Self::Illegal => "Illegal",
Self::Trap => "Trap",
Self::Abort => "Abort",
Self::IOT => "IOT",
Self::Bus => "Bus",
Self::FloatingPointException => "FloatingPointException",
Self::Kill => "Kill",
Self::User1 => "User1",
Self::Segv => "Segv",
Self::User2 => "User2",
Self::Pipe => "Pipe",
Self::Alarm => "Alarm",
Self::Term => "Term",
Self::Child => "Child",
Self::Continue => "Continue",
Self::Stop => "Stop",
Self::TSTP => "TSTP",
Self::TTIN => "TTIN",
Self::TTOU => "TTOU",
Self::Urgent => "Urgent",
Self::XCPU => "XCPU",
Self::XFSZ => "XFSZ",
Self::VirtualAlarm => "VirtualAlarm",
Self::Profiling => "Profiling",
Self::Winch => "Winch",
Self::IO => "IO",
Self::Poll => "Poll",
Self::Power => "Power",
Self::Sys => "Sys",
};
f.write_str(s)
}
}
/// Contains memory limits for the current process.
#[derive(Default, Debug, Clone)]
pub struct CGroupLimits {
/// Total memory (in bytes) for the current cgroup.
pub total_memory: u64,
/// Free memory (in bytes) for the current cgroup.
pub free_memory: u64,
/// Free swap (in bytes) for the current cgroup.
pub free_swap: u64,
/// Resident Set Size (RSS) (in bytes) for the current cgroup.
pub rss: u64,
}
/// Type containing read and written bytes.
///
/// It is returned by [`Process::disk_usage`][crate::Process::disk_usage].
///
/// ```no_run
/// use sysinfo::System;
///
/// let s = System::new_all();
/// for (pid, process) in s.processes() {
/// let disk_usage = process.disk_usage();
/// println!("[{}] read bytes : new/total => {}/{} B",
/// pid,
/// disk_usage.read_bytes,
/// disk_usage.total_read_bytes,
/// );
/// println!("[{}] written bytes: new/total => {}/{} B",
/// pid,
/// disk_usage.written_bytes,
/// disk_usage.total_written_bytes,
/// );
/// }
/// ```
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub struct DiskUsage {
/// Total number of written bytes.
pub total_written_bytes: u64,
/// Number of written bytes since the last refresh.
pub written_bytes: u64,
/// Total number of read bytes.
pub total_read_bytes: u64,
/// Number of read bytes since the last refresh.
pub read_bytes: u64,
}
/// Enum describing the different status of a process.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProcessStatus {
/// ## Linux
///
/// Idle kernel thread.
///
/// ## macOs/FreeBSD
///
/// Process being created by fork.
///
/// ## Other OS
///
/// Not available.
Idle,
/// Running.
Run,
/// ## Linux