Skip to main content

sysinfo/common/
system.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::collections::{HashMap, HashSet};
4use std::ffi::{OsStr, OsString};
5use std::fmt;
6use std::path::Path;
7use std::process::ExitStatus;
8use std::str::FromStr;
9
10use crate::common::DiskUsage;
11use crate::common::impl_get_set::impl_get_set;
12use crate::{CpuInner, Error, Gid, MotherboardInner, ProcessInner, ProductInner, SystemInner, Uid};
13
14/// Type containing system's information such as processes, memory and CPU.
15///
16/// ⚠️ On newer Android versions, there are restrictions on which system information
17/// a non-system application has access to. So CPU information might not be available.
18///
19/// ```
20/// use sysinfo::System;
21///
22/// match System::new_all() {
23///     Ok(system) => println!("System: {system:?}"),
24///     Err(error) => println!("Failed to initialize system: {error:?}"),
25/// }
26/// ```
27pub struct System {
28    pub(crate) inner: SystemInner,
29}
30
31impl System {
32    /// Creates a new [`System`] instance with nothing loaded.
33    ///
34    /// Use one of the refresh methods (like [`refresh_all`]) to update its internal information.
35    ///
36    /// [`System`]: crate::System
37    /// [`refresh_all`]: #method.refresh_all
38    ///
39    /// ```no_run
40    /// use sysinfo::System;
41    ///
42    /// let Ok(s) = System::new() else {
43    ///     println!("Failed to initialize `System`");
44    ///     return;
45    /// };
46    /// ```
47    pub fn new() -> Result<Self, Error> {
48        Self::new_with_specifics(RefreshKind::nothing())
49    }
50
51    /// Creates a new [`System`] instance with everything loaded.
52    ///
53    /// It is an equivalent of [`System::new_with_specifics`]`(`[`RefreshKind::everything`]`())`.
54    ///
55    /// [`System`]: crate::System
56    ///
57    /// ```no_run
58    /// use sysinfo::System;
59    ///
60    /// let Ok(s) = System::new_all() else {
61    ///     println!("Failed to initialize `System`");
62    ///     return;
63    /// };
64    /// ```
65    pub fn new_all() -> Result<Self, Error> {
66        Self::new_with_specifics(RefreshKind::everything())
67    }
68
69    /// Creates a new [`System`] instance and refresh the data corresponding to the
70    /// given [`RefreshKind`].
71    ///
72    /// [`System`]: crate::System
73    ///
74    /// ```
75    /// use sysinfo::{ProcessRefreshKind, RefreshKind, System};
76    ///
77    /// // We want to only refresh processes.
78    /// if let Ok(mut system) = System::new_with_specifics(
79    ///      RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
80    /// ) {
81    /// # if !cfg!(feature = "apple-sandbox") {
82    ///     assert!(!system.processes().is_empty());
83    /// # }
84    /// }
85    /// ```
86    pub fn new_with_specifics(refreshes: RefreshKind) -> Result<Self, Error> {
87        let mut s = Self {
88            inner: SystemInner::new()?,
89        };
90        s.refresh_specifics(refreshes);
91        Ok(s)
92    }
93
94    /// Refreshes according to the given [`RefreshKind`]. It calls the corresponding
95    /// "refresh_" methods.
96    ///
97    /// It will remove dead processes if [`RefreshKind::processes`] returns `Some`.
98    /// If you want to keep dead processes, use [`System::refresh_processes_specifics`]
99    /// directly.
100    ///
101    /// ```
102    /// use sysinfo::{ProcessRefreshKind, RefreshKind, System};
103    ///
104    /// if let Ok(mut s) = System::new_all() {
105    ///     // Let's just update processes:
106    ///     s.refresh_specifics(
107    ///         RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
108    ///     );
109    /// }
110    /// ```
111    pub fn refresh_specifics(&mut self, refreshes: RefreshKind) {
112        if let Some(kind) = refreshes.memory() {
113            self.refresh_memory_specifics(kind);
114        }
115        if let Some(kind) = refreshes.cpu() {
116            self.refresh_cpu_specifics(kind);
117        }
118        if let Some(kind) = refreshes.processes() {
119            self.refresh_processes_specifics(ProcessesToUpdate::All, true, kind);
120        }
121    }
122
123    /// Refreshes all system and processes information.
124    ///
125    /// It is the same as calling `system.refresh_specifics(RefreshKind::everything())`.
126    ///
127    /// Don't forget to take a look at [`ProcessRefreshKind::everything`] method to see what it
128    /// will update for processes more in details.
129    ///
130    /// It will remove dead processes. If you want to keep dead processes, use
131    /// [`System::refresh_processes_specifics`] directly.
132    ///
133    /// ```no_run
134    /// use sysinfo::System;
135    ///
136    /// if let Ok(mut s) = System::new() {
137    ///     s.refresh_all();
138    /// }
139    /// ```
140    pub fn refresh_all(&mut self) {
141        self.refresh_specifics(RefreshKind::everything());
142    }
143
144    /// Refreshes RAM and SWAP usage.
145    ///
146    /// It is the same as calling `system.refresh_memory_specifics(MemoryRefreshKind::everything())`.
147    ///
148    /// If you don't want to refresh both, take a look at [`System::refresh_memory_specifics`].
149    ///
150    /// ```no_run
151    /// use sysinfo::System;
152    ///
153    /// if let Ok(mut s) = System::new() {
154    ///     s.refresh_memory();
155    /// }
156    /// ```
157    pub fn refresh_memory(&mut self) {
158        self.refresh_memory_specifics(MemoryRefreshKind::everything())
159    }
160
161    /// Refreshes system memory specific information.
162    ///
163    /// ```no_run
164    /// use sysinfo::{MemoryRefreshKind, System};
165    ///
166    /// if let Ok(mut s) = System::new() {
167    ///     s.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
168    /// }
169    /// ```
170    pub fn refresh_memory_specifics(&mut self, refresh_kind: MemoryRefreshKind) {
171        self.inner.refresh_memory_specifics(refresh_kind)
172    }
173
174    /// Refreshes CPUs usage.
175    ///
176    /// ⚠️ Please note that the result will very likely be inaccurate at the first call.
177    /// You need to call this method at least twice (with a bit of time between each call, like
178    /// 200 ms, take a look at [`MINIMUM_CPU_UPDATE_INTERVAL`] for more information)
179    /// to get accurate value as it uses previous results to compute the next value.
180    ///
181    /// Calling this method is the same as calling
182    /// `system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_usage())`.
183    ///
184    /// ```no_run
185    /// use sysinfo::System;
186    ///
187    /// if let Ok(mut s) = System::new_all() {
188    ///     // Wait a bit because CPU usage is based on diff.
189    ///     std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
190    ///     // Refresh CPUs again.
191    ///     s.refresh_cpu_usage();
192    /// }
193    /// ```
194    ///
195    /// [`MINIMUM_CPU_UPDATE_INTERVAL`]: crate::MINIMUM_CPU_UPDATE_INTERVAL
196    pub fn refresh_cpu_usage(&mut self) {
197        self.refresh_cpu_specifics(CpuRefreshKind::nothing().with_usage())
198    }
199
200    /// Refreshes CPUs frequency information.
201    ///
202    /// Calling this method is the same as calling
203    /// `system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_frequency())`.
204    ///
205    /// ```no_run
206    /// use sysinfo::System;
207    ///
208    /// if let Ok(mut s) = System::new_all() {
209    ///     s.refresh_cpu_frequency();
210    /// }
211    /// ```
212    pub fn refresh_cpu_frequency(&mut self) {
213        self.refresh_cpu_specifics(CpuRefreshKind::nothing().with_frequency())
214    }
215
216    /// Refreshes the list of CPU.
217    ///
218    /// Normally, this should almost never be needed as it's pretty rare for a computer
219    /// to add a CPU while running, but it's possible on some computers which shutdown
220    /// CPU if the load is low enough.
221    ///
222    /// The `refresh_kind` argument tells what information you want to be retrieved
223    /// for each CPU.
224    ///
225    /// ```no_run
226    /// use sysinfo::{CpuRefreshKind, System};
227    ///
228    /// if let Ok(mut s) = System::new_all() {
229    ///     // We already have the list of CPU filled, but we want to recompute it
230    ///     // in case new CPUs were added.
231    ///     s.refresh_cpu_list(CpuRefreshKind::everything());
232    /// }
233    /// ```
234    pub fn refresh_cpu_list(&mut self, refresh_kind: CpuRefreshKind) {
235        self.inner.refresh_cpu_list(refresh_kind);
236    }
237
238    /// Refreshes all information related to CPUs information. It does not refresh the CPU list.
239    /// If you want to refresh the CPU list, use [`System::refresh_cpu_list`] instead.
240    ///
241    /// If you only want the CPU usage, use [`System::refresh_cpu_usage`] instead.
242    ///
243    /// ⚠️ Please note that the result will be inaccurate at the first call.
244    /// You need to call this method at least twice (with a bit of time between each call, like
245    /// 200 ms, take a look at [`MINIMUM_CPU_UPDATE_INTERVAL`] for more information)
246    /// to get accurate value as it uses previous results to compute the next value.
247    ///
248    /// Calling this method is the same as calling
249    /// `system.refresh_cpu_specifics(CpuRefreshKind::everything())`.
250    ///
251    /// ```no_run
252    /// use sysinfo::System;
253    ///
254    /// if let Ok(mut s) = System::new_all() {
255    ///     s.refresh_cpu_all();
256    /// }
257    /// ```
258    ///
259    /// [`MINIMUM_CPU_UPDATE_INTERVAL`]: crate::MINIMUM_CPU_UPDATE_INTERVAL
260    pub fn refresh_cpu_all(&mut self) {
261        self.refresh_cpu_specifics(CpuRefreshKind::everything())
262    }
263
264    /// Refreshes CPUs specific information. It does not refresh the CPU list.
265    /// If you want to refresh the CPU list, use [`System::refresh_cpu_list`] instead.
266    ///
267    /// ```no_run
268    /// use sysinfo::{System, CpuRefreshKind};
269    ///
270    /// if let Ok(mut s) = System::new_all() {
271    ///     s.refresh_cpu_specifics(CpuRefreshKind::everything());
272    /// }
273    /// ```
274    pub fn refresh_cpu_specifics(&mut self, refresh_kind: CpuRefreshKind) {
275        self.inner.refresh_cpu_specifics(refresh_kind)
276    }
277
278    /// Gets all processes and updates their information, along with all the tasks each process has.
279    ///
280    /// It does the same as:
281    ///
282    /// ```no_run
283    /// # use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System, UpdateKind};
284    /// # if let Ok(mut system) = System::new() {
285    /// system.refresh_processes_specifics(
286    ///     ProcessesToUpdate::All,
287    ///     true,
288    ///     ProcessRefreshKind::nothing()
289    ///         .with_memory()
290    ///         .with_cpu()
291    ///         .with_disk_usage()
292    ///         .with_exe(UpdateKind::OnlyIfNotSet)
293    ///         .with_tasks()
294    /// );
295    /// # }
296    /// ```
297    ///
298    /// ⚠️ `remove_dead_processes` works as follows: if an updated process is dead, then it is
299    /// removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed
300    /// since 7 is not part of the update.
301    ///
302    /// ⚠️ On Linux, if you dont need the tasks of each process, you can use
303    /// `refresh_processes_specifics` with `ProcessRefreshKind::everything().without_tasks()`.
304    /// Refreshing all processes and their tasks can be quite expensive. For more information
305    /// see [`ProcessRefreshKind`].
306    ///
307    /// Example:
308    ///
309    /// ```no_run
310    /// use sysinfo::{ProcessesToUpdate, System};
311    ///
312    /// if let Ok(mut s) = System::new_all() {
313    ///     s.refresh_processes(ProcessesToUpdate::All, true);
314    /// }
315    /// ```
316    pub fn refresh_processes(
317        &mut self,
318        processes_to_update: ProcessesToUpdate<'_>,
319        remove_dead_processes: bool,
320    ) -> usize {
321        self.refresh_processes_specifics(
322            processes_to_update,
323            remove_dead_processes,
324            ProcessRefreshKind::nothing()
325                .with_memory()
326                .with_cpu()
327                .with_disk_usage()
328                .with_exe(UpdateKind::OnlyIfNotSet)
329                .with_tasks(),
330        )
331    }
332
333    /// Gets all processes and updates the specified information.
334    ///
335    /// Returns the number of updated processes.
336    ///
337    /// ⚠️ `remove_dead_processes` works as follows: if an updated process is dead, then it is
338    /// removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed
339    /// since 7 is not part of the update.
340    ///
341    /// ```no_run
342    /// use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System};
343    ///
344    /// if let Ok(mut s) = System::new_all() {
345    ///     s.refresh_processes_specifics(
346    ///         ProcessesToUpdate::All,
347    ///         true,
348    ///         ProcessRefreshKind::everything(),
349    ///     );
350    /// }
351    /// ```
352    pub fn refresh_processes_specifics(
353        &mut self,
354        processes_to_update: ProcessesToUpdate<'_>,
355        remove_dead_processes: bool,
356        refresh_kind: ProcessRefreshKind,
357    ) -> usize {
358        // FIXME: Replace the slice with a `&HashSet<Pid>`.
359        let mut data;
360        let processes_to_update = match processes_to_update {
361            ProcessesToUpdate::All => ProcessesToUpdate::All,
362            ProcessesToUpdate::Some(pids) => {
363                data = pids.to_vec();
364                data.sort_unstable();
365                data.dedup();
366                ProcessesToUpdate::Some(data.as_slice())
367            }
368        };
369        let nb_updated = self
370            .inner
371            .refresh_processes_specifics(processes_to_update, refresh_kind);
372
373        // FIXME: This code is absolutely awful, find a better way to do the same (ie remove GPU
374        // counters when removing a process) in a code which doesn't need all that...
375        cfg_select! {
376            all(windows, feature = "gpu") => {
377                fn update_and_remove(
378                    pid: &Pid,
379                    processes: &mut HashMap<Pid, Process>,
380                    gpu_query: &mut Option<crate::sys::cpu::Query>,
381                ) {
382                    if let Some(proc) = processes.get_mut(pid) {
383                        let updated = proc.inner.switch_updated();
384                        if !updated {
385                            proc.inner.remove_counter(gpu_query);
386                            processes.remove(pid);
387                        }
388                    }
389                }
390                fn update(
391                    pid: &Pid,
392                    processes: &mut HashMap<Pid, Process>,
393                    _gpu_query: &mut Option<crate::sys::cpu::Query>,
394                ) {
395                    if let Some(proc) = processes.get_mut(pid)
396                        && !proc.inner.switch_updated()
397                    {
398                        proc.inner.set_nonexistent();
399                    }
400                }
401
402                let mut gpu_query = self.inner.gpu_query.take();
403                let processes = self.inner.processes_mut();
404                match processes_to_update {
405                    ProcessesToUpdate::All => {
406                        if remove_dead_processes {
407                            processes.retain(|_, v| {
408                                let to_keep = v.inner.switch_updated();
409                                if !to_keep {
410                                    v.inner.remove_counter(&mut gpu_query);
411                                }
412                                to_keep
413                            });
414                        } else {
415                            for proc in processes.values_mut() {
416                                proc.inner.switch_updated();
417                            }
418                        }
419                    }
420                    ProcessesToUpdate::Some(pids) => {
421                        let call = if remove_dead_processes {
422                            update_and_remove
423                        } else {
424                            update
425                        };
426                        for pid in pids {
427                            call(pid, processes, &mut gpu_query);
428                        }
429                    }
430                }
431                self.inner.gpu_query = gpu_query;
432            }
433            _ => {
434                fn update_and_remove(pid: &Pid, processes: &mut HashMap<Pid, Process>) {
435                    let updated = if let Some(proc) = processes.get_mut(pid) {
436                        proc.inner.switch_updated()
437                    } else {
438                        return;
439                    };
440                    if !updated {
441                        processes.remove(pid);
442                    }
443                }
444                fn update(pid: &Pid, processes: &mut HashMap<Pid, Process>) {
445                    if let Some(proc) = processes.get_mut(pid)
446                        && !proc.inner.switch_updated()
447                    {
448                        proc.inner.set_nonexistent();
449                    }
450                }
451
452                let processes = self.inner.processes_mut();
453                match processes_to_update {
454                    ProcessesToUpdate::All => {
455                        if remove_dead_processes {
456                            processes.retain(|_, v| v.inner.switch_updated());
457                        } else {
458                            for proc in processes.values_mut() {
459                                proc.inner.switch_updated();
460                            }
461                        }
462                    }
463                    ProcessesToUpdate::Some(pids) => {
464                        let call = if remove_dead_processes {
465                            update_and_remove
466                        } else {
467                            update
468                        };
469                        for pid in pids {
470                            call(pid, processes);
471                        }
472                    }
473                }
474            }
475        }
476        nb_updated
477    }
478
479    /// Returns the process list.
480    ///
481    /// ```no_run
482    /// use sysinfo::System;
483    ///
484    /// if let Ok(s) = System::new_all() {
485    ///     for (pid, process) in s.processes() {
486    ///         println!("{} {:?}", pid, process.name());
487    ///     }
488    /// }
489    /// ```
490    pub fn processes(&self) -> &HashMap<Pid, Process> {
491        self.inner.processes()
492    }
493
494    /// Returns the process corresponding to the given `pid` or `None` if no such process exists.
495    ///
496    /// ```no_run
497    /// use sysinfo::{Pid, System};
498    ///
499    /// if let Ok(s) = System::new_all() {
500    ///     if let Some(process) = s.process(Pid::from(1337)) {
501    ///         println!("{:?}", process.name());
502    ///     }
503    /// }
504    /// ```
505    pub fn process(&self, pid: Pid) -> Option<&Process> {
506        self.inner.process(pid)
507    }
508
509    /// Returns an iterator of process containing the given `name`.
510    ///
511    /// If you want only the processes with exactly the given `name`, take a look at
512    /// [`System::processes_by_exact_name`].
513    ///
514    /// **⚠️ Important ⚠️**
515    ///
516    /// On **Linux**, there are two things to know about processes' name:
517    ///  1. It is limited to 15 characters.
518    ///  2. It is not always the exe name.
519    ///
520    /// ```no_run
521    /// use sysinfo::System;
522    ///
523    /// if let Ok(s) = System::new_all() {
524    ///     for process in s.processes_by_name("htop".as_ref()) {
525    ///         println!("{} {:?}", process.pid(), process.name());
526    ///     }
527    /// }
528    /// ```
529    pub fn processes_by_name<'a: 'b, 'b>(
530        &'a self,
531        name: &'b OsStr,
532    ) -> impl Iterator<Item = &'a Process> + 'b {
533        let finder = memchr::memmem::Finder::new(name.as_encoded_bytes());
534        self.processes()
535            .values()
536            .filter(move |val: &&Process| finder.find(val.name().as_encoded_bytes()).is_some())
537    }
538
539    /// Returns an iterator of processes with exactly the given `name`.
540    ///
541    /// If you instead want the processes containing `name`, take a look at
542    /// [`System::processes_by_name`].
543    ///
544    /// **⚠️ Important ⚠️**
545    ///
546    /// On **Linux**, there are two things to know about processes' name:
547    ///  1. It is limited to 15 characters.
548    ///  2. It is not always the exe name.
549    ///
550    /// ```no_run
551    /// use sysinfo::System;
552    ///
553    /// if let Ok(s) = System::new_all() {
554    ///     for process in s.processes_by_exact_name("htop".as_ref()) {
555    ///         println!("{} {:?}", process.pid(), process.name());
556    ///     }
557    /// }
558    /// ```
559    pub fn processes_by_exact_name<'a: 'b, 'b>(
560        &'a self,
561        name: &'b OsStr,
562    ) -> impl Iterator<Item = &'a Process> + 'b {
563        self.processes()
564            .values()
565            .filter(move |val: &&Process| val.name() == name)
566    }
567
568    /// Returns "global" CPUs usage (aka the addition of all the CPUs).
569    ///
570    /// To have up-to-date information, you need to call [`System::refresh_cpu_specifics`] or
571    /// [`System::refresh_specifics`] with `cpu` enabled.
572    ///
573    /// ```no_run
574    /// use sysinfo::{CpuRefreshKind, RefreshKind, System};
575    ///
576    /// if let Ok(mut s) = System::new_with_specifics(
577    ///     RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
578    /// ) {
579    ///     // Wait a bit because CPU usage is based on diff.
580    ///     std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
581    ///     // Refresh CPUs again to get actual value.
582    ///     s.refresh_cpu_usage();
583    ///     println!("{}%", s.global_cpu_usage());
584    /// }
585    /// ```
586    pub fn global_cpu_usage(&self) -> f32 {
587        self.inner.global_cpu_usage()
588    }
589
590    /// Returns the list of the CPUs.
591    ///
592    /// By default, the list of CPUs is empty until you call [`System::refresh_cpu_specifics`] or
593    /// [`System::refresh_specifics`] with `cpu` enabled.
594    ///
595    /// ```no_run
596    /// use sysinfo::{CpuRefreshKind, RefreshKind, System};
597    ///
598    /// if let Ok(mut s) = System::new_with_specifics(
599    ///     RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
600    /// ) {
601    ///     // Wait a bit because CPU usage is based on diff.
602    ///     std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
603    ///     // Refresh CPUs again to get actual value.
604    ///     s.refresh_cpu_usage();
605    ///     for cpu in s.cpus() {
606    ///         println!("{}%", cpu.usage());
607    ///     }
608    /// }
609    /// ```
610    pub fn cpus(&self) -> &[Cpu] {
611        self.inner.cpus()
612    }
613
614    /// Returns the RAM size in bytes.
615    ///
616    /// ```no_run
617    /// use sysinfo::System;
618    ///
619    /// if let Ok(s) = System::new_all() {
620    ///     println!("{} bytes", s.total_memory());
621    /// }
622    /// ```
623    ///
624    /// On Linux, if you want to see this information with the limit of your cgroup, take a look
625    /// at [`cgroup_limits`](System::cgroup_limits).
626    pub fn total_memory(&self) -> u64 {
627        self.inner.total_memory()
628    }
629
630    /// Returns the amount of free RAM in bytes.
631    ///
632    /// Generally, "free" memory refers to unallocated memory whereas "available" memory refers to
633    /// memory that is available for (re)use.
634    ///
635    /// Side note: Windows doesn't report "free" memory so this method returns the same value
636    /// as [`available_memory`](System::available_memory).
637    ///
638    /// ```no_run
639    /// use sysinfo::System;
640    ///
641    /// if let Ok(s) = System::new_all() {
642    ///     println!("{} bytes", s.free_memory());
643    /// }
644    /// ```
645    pub fn free_memory(&self) -> u64 {
646        self.inner.free_memory()
647    }
648
649    /// Returns the amount of available RAM in bytes.
650    ///
651    /// Generally, "free" memory refers to unallocated memory whereas "available" memory refers to
652    /// memory that is available for (re)use.
653    ///
654    /// ⚠️ Windows doesn't report "available" memory so [`System::free_memory`]
655    /// returns the same value as this method.
656    ///
657    /// ```no_run
658    /// use sysinfo::System;
659    ///
660    /// if let Ok(s) = System::new_all() {
661    ///     println!("{} bytes", s.available_memory());
662    /// }
663    /// ```
664    pub fn available_memory(&self) -> u64 {
665        self.inner.available_memory()
666    }
667
668    /// Returns the amount of used RAM in bytes.
669    ///
670    /// ```no_run
671    /// use sysinfo::System;
672    ///
673    /// if let Ok(s) = System::new_all() {
674    ///     println!("{} bytes", s.used_memory());
675    /// }
676    /// ```
677    pub fn used_memory(&self) -> u64 {
678        self.inner.used_memory()
679    }
680
681    /// Returns the SWAP size in bytes.
682    ///
683    /// ```no_run
684    /// use sysinfo::System;
685    ///
686    /// if let Ok(s) = System::new_all() {
687    ///     println!("{} bytes", s.total_swap());
688    /// }
689    /// ```
690    pub fn total_swap(&self) -> u64 {
691        self.inner.total_swap()
692    }
693
694    /// Returns the amount of free SWAP in bytes.
695    ///
696    /// ```no_run
697    /// use sysinfo::System;
698    ///
699    /// if let Ok(s) = System::new_all() {
700    ///     println!("{} bytes", s.free_swap());
701    /// }
702    /// ```
703    pub fn free_swap(&self) -> u64 {
704        self.inner.free_swap()
705    }
706
707    /// Returns the amount of used SWAP in bytes.
708    ///
709    /// ```no_run
710    /// use sysinfo::System;
711    ///
712    /// if let Ok(s) = System::new_all() {
713    ///     println!("{} bytes", s.used_swap());
714    /// }
715    /// ```
716    pub fn used_swap(&self) -> u64 {
717        self.inner.used_swap()
718    }
719
720    /// Retrieves the limits for the root cgroup (if any), otherwise it returns `None`.
721    ///
722    /// This information is computed every time the method is called.
723    ///
724    /// ⚠️ This method is only implemented for Linux. It always returns `None` for all other
725    /// systems.
726    ///
727    /// ```no_run
728    /// use sysinfo::System;
729    ///
730    /// if let Ok(s) = System::new_all() {
731    ///     println!("limits: {:?}", s.cgroup_limits());
732    /// }
733    /// ```
734    pub fn cgroup_limits(&self) -> Option<CGroupLimits> {
735        self.inner.cgroup_limits()
736    }
737
738    /// Returns system uptime (in seconds).
739    ///
740    /// **Important**: this information is computed every time this function is called.
741    ///
742    /// ```no_run
743    /// use sysinfo::System;
744    ///
745    /// match System::uptime() {
746    ///     Ok(uptime) => println!("System running since {uptime} seconds"),
747    ///     Err(error) => eprintln!("Failed to get `uptime`: {error}"),
748    /// }
749    /// ```
750    pub fn uptime() -> Result<u64, Error> {
751        SystemInner::uptime()
752    }
753
754    /// Returns the time (in seconds) when the system booted since UNIX epoch.
755    ///
756    /// **Important**: this information is computed every time this function is called.
757    ///
758    /// ```no_run
759    /// use sysinfo::System;
760    ///
761    /// match System::boot_time() {
762    ///     Ok(boot_time) => println!("System booted at {boot_time} seconds"),
763    ///     Err(error) => eprintln!("Failed to get `boot_time`: {error}"),
764    /// }
765    /// ```
766    pub fn boot_time() -> Result<u64, Error> {
767        SystemInner::boot_time()
768    }
769
770    /// Returns the system load average value.
771    ///
772    /// **Important**: this information is computed every time this function is called.
773    ///
774    /// ⚠️ This is currently not working on **Windows**.
775    ///
776    /// ```no_run
777    /// use sysinfo::System;
778    ///
779    /// match System::load_average() {
780    ///     Ok(load_avg) => {
781    ///         println!(
782    ///             "one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
783    ///             load_avg.one,
784    ///             load_avg.five,
785    ///             load_avg.fifteen,
786    ///         );
787    ///     }
788    ///     Err(error) => eprintln!("Failed to get `load_average`: {error}"),
789    /// }
790    /// ```
791    pub fn load_average() -> Result<LoadAvg, Error> {
792        SystemInner::load_average()
793    }
794
795    /// Returns the system name.
796    ///
797    /// | example platform | value of `System::name()` |
798    /// |---|---|
799    /// | linux laptop | "Ubuntu" |
800    /// | android phone | "Pixel 9 Pro" |
801    /// | apple laptop | "Darwin" |
802    /// | windows server | "Windows" |
803    ///
804    /// **Important**: this information is computed every time this function is called.
805    ///
806    /// ```no_run
807    /// use sysinfo::System;
808    ///
809    /// println!("OS: {:?}", System::name());
810    /// ```
811    pub fn name() -> Result<String, Error> {
812        SystemInner::name()
813    }
814
815    /// Returns the system's kernel version.
816    ///
817    /// | example platform | value of `System::kernel_version()` |
818    /// |---|---|
819    /// | linux laptop | "6.8.0-48-generic" |
820    /// | android phone | "6.1.84-android14-11" |
821    /// | apple laptop | "24.1.0" |
822    /// | windows server | "20348" |
823    ///
824    /// **Important**: this information is computed every time this function is called.
825    ///
826    /// ```no_run
827    /// use sysinfo::System;
828    ///
829    /// println!("kernel version: {:?}", System::kernel_version());
830    /// ```
831    pub fn kernel_version() -> Result<String, Error> {
832        SystemInner::kernel_version()
833    }
834
835    /// Returns the system version (e.g. for macOS this will return 15.1 rather than the kernel
836    /// version).
837    ///
838    /// | example platform | value of `System::os_version()` |
839    /// |---|---|
840    /// | linux laptop | "24.04" |
841    /// | android phone | "15" |
842    /// | apple laptop | "15.1.1" |
843    /// | windows server | "10 (20348)" |
844    ///
845    /// **Important**: this information is computed every time this function is called.
846    ///
847    /// ```no_run
848    /// use sysinfo::System;
849    ///
850    /// println!("OS version: {:?}", System::os_version());
851    /// ```
852    pub fn os_version() -> Result<String, Error> {
853        SystemInner::os_version()
854    }
855
856    /// Returns the system long os version.
857    ///
858    /// | example platform | value of `System::long_os_version()` |
859    /// |---|---|
860    /// | linux laptop | "Linux (Ubuntu 24.04)" |
861    /// | android phone | "Android 15 on Pixel 9 Pro" |
862    /// | apple laptop | "macOS 15.1.1 Sequoia" |
863    /// | windows server | "Windows Server 2022 Datacenter" |
864    ///
865    /// **Important**: this information is computed every time this function is called.
866    ///
867    /// ```no_run
868    /// use sysinfo::System;
869    ///
870    /// println!("Long OS Version: {:?}", System::long_os_version());
871    /// ```
872    pub fn long_os_version() -> Result<String, Error> {
873        SystemInner::long_os_version()
874    }
875
876    /// Returns the distribution id as defined by os-release,
877    /// or [`std::env::consts::OS`].
878    ///
879    /// See also
880    /// - <https://www.freedesktop.org/software/systemd/man/os-release.html#ID=>
881    /// - <https://doc.rust-lang.org/std/env/consts/constant.OS.html>
882    ///
883    /// | example platform | value of `System::distribution_id()` |
884    /// |---|---|
885    /// | linux laptop | "ubuntu" |
886    /// | android phone | "android" |
887    /// | apple laptop | "macos" |
888    /// | windows server | "windows" |
889    ///
890    /// **Important**: this information is computed every time this function is called.
891    ///
892    /// ```no_run
893    /// use sysinfo::System;
894    ///
895    /// println!("Distribution ID: {:?}", System::distribution_id());
896    /// ```
897    pub fn distribution_id() -> String {
898        SystemInner::distribution_id()
899    }
900
901    /// Returns the distribution ids of operating systems that are closely
902    /// related to the local operating system in regards to packaging and
903    /// programming interfaces, for example listing one or more OS identifiers
904    /// the local OS is a derivative from.
905    ///
906    /// See also
907    /// - <https://www.freedesktop.org/software/systemd/man/latest/os-release.html#ID_LIKE=>
908    ///
909    /// | example platform | value of `System::distribution_id_like()` |
910    /// |---|---|
911    /// | android phone | [] |
912    /// | archlinux laptop | [] |
913    /// | centos server | ["rhel", "fedora"] |
914    /// | ubuntu laptop | ["debian"] |
915    /// | windows laptop | [] |
916    ///
917    /// **Important**: this information is computed every time this function is called.
918    ///
919    /// ```no_run
920    /// use sysinfo::System;
921    ///
922    /// println!("Distribution ID_LIKE: {:?}", System::distribution_id_like());
923    /// ```
924    pub fn distribution_id_like() -> Vec<String> {
925        SystemInner::distribution_id_like()
926    }
927
928    /// Provides kernel version following this string format:
929    ///
930    /// | Platform | Result |
931    /// |-|-|
932    /// | Windows | Windows OS Build 20348.2227 |
933    /// | Linux | Linux 6.12.13-200.fc41.x86_64 |
934    /// | Android | Android 612.13-200 |
935    /// | MacOS | Darwin 21.6.0 |
936    /// | FreeBSD | FreeBSD 199506 |
937    ///
938    /// If any of the information is not available, it will be replaced with "unknown".
939    ///
940    /// **Important**: this information is computed every time this function is called.
941    ///
942    /// ```no_run
943    /// use sysinfo::System;
944    ///
945    /// println!("Kernel long version: {:?}", System::kernel_long_version());
946    /// ```
947    ///
948    /// [distribution_id]: System::distribution_id
949    /// [kernel_version]: System::kernel_version
950    pub fn kernel_long_version() -> Result<String, Error> {
951        let Some(kernel_name) = SystemInner::kernel_name() else {
952            return Err(Error::Unsupported);
953        };
954        let kernel_version = System::kernel_version();
955        let kernel_version = kernel_version.as_deref().unwrap_or("Unknown");
956        Ok(if cfg!(windows) {
957            format!("{kernel_name} OS Build {kernel_version}")
958        } else {
959            format!("{kernel_name} {kernel_version}")
960        })
961    }
962
963    /// Returns the system hostname based off DNS.
964    ///
965    /// **Important**: this information is computed every time this function is called.
966    ///
967    /// ```no_run
968    /// use sysinfo::System;
969    ///
970    /// println!("Hostname: {:?}", System::host_name());
971    /// ```
972    pub fn host_name() -> Result<String, Error> {
973        SystemInner::host_name()
974    }
975
976    /// Returns the CPU architecture (eg. x86, amd64, aarch64, ...).
977    ///
978    /// **Important**: this information is computed every time this function is called.
979    ///
980    /// ```no_run
981    /// use sysinfo::System;
982    ///
983    /// println!("CPU Architecture: {:?}", System::cpu_arch());
984    /// ```
985    pub fn cpu_arch() -> String {
986        SystemInner::cpu_arch().unwrap_or_else(|| std::env::consts::ARCH.to_owned())
987    }
988
989    /// Returns the number of physical cores on the CPU.
990    ///
991    /// In case there are multiple CPUs, it will combine the physical core count of all the CPUs.
992    ///
993    /// **Important**: this information is computed every time this function is called.
994    ///
995    /// ```no_run
996    /// use sysinfo::System;
997    ///
998    /// if let Ok(s) = System::new() {
999    ///     println!("{:?}", System::physical_core_count());
1000    /// }
1001    /// ```
1002    pub fn physical_core_count() -> Result<usize, Error> {
1003        SystemInner::physical_core_count()
1004    }
1005
1006    /// Returns the (default) maximum number of open files for a process.
1007    ///
1008    /// **Important**: this information is computed every time this function is called.
1009    ///
1010    /// ```no_run
1011    /// use sysinfo::System;
1012    ///
1013    /// println!("Max open files: {:?}", System::open_files_limit());
1014    /// ```
1015    pub fn open_files_limit() -> Result<usize, Error> {
1016        SystemInner::open_files_limit()
1017    }
1018}
1019
1020/// This type allows to retrieve motherboard-related information.
1021///
1022/// ⚠️ Not implemented on NetBSD.
1023///
1024/// ```
1025/// use sysinfo::Motherboard;
1026///
1027/// if let Ok(m) = Motherboard::new() {
1028///     println!("{m:?}");
1029/// }
1030/// ```
1031pub struct Motherboard {
1032    pub(crate) inner: MotherboardInner,
1033}
1034
1035impl Motherboard {
1036    /// Creates a new instance of the `Motherboard` type.
1037    ///
1038    /// ```
1039    /// use sysinfo::Motherboard;
1040    ///
1041    /// if let Ok(m) = Motherboard::new() {
1042    ///     println!("{m:?}");
1043    /// }
1044    /// ```
1045    pub fn new() -> Result<Self, Error> {
1046        Ok(Self {
1047            inner: MotherboardInner::new()?,
1048        })
1049    }
1050
1051    /// Returns the motherboard name.
1052    ///
1053    /// This corresponds to the model identifier assigned by the motherboard's
1054    /// manufacturer (e.g. "20BE0061MC").
1055    /// This information isn't available on ARM-based macOS systems.
1056    ///
1057    /// **Important**: this information is computed every time this function is called.
1058    ///
1059    /// ```no_run
1060    /// use sysinfo::Motherboard;
1061    ///
1062    /// if let Ok(m) = Motherboard::new() {
1063    ///     println!("Motherboard name: {:?}", m.name());
1064    /// }
1065    /// ```
1066    pub fn name(&self) -> Option<String> {
1067        self.inner.name()
1068    }
1069
1070    /// Returns the motherboard vendor name.
1071    ///
1072    /// This corresponds to the name of the motherboard's manufacturer (e.g. "LENOVO").
1073    ///
1074    /// **Important**: this information is computed every time this function is called.
1075    ///
1076    /// ```no_run
1077    /// use sysinfo::Motherboard;
1078    ///
1079    /// if let Ok(m) = Motherboard::new() {
1080    ///     println!("Motherboard vendor: {:?}", m.vendor_name());
1081    /// }
1082    /// ```
1083    pub fn vendor_name(&self) -> Option<String> {
1084        self.inner.vendor_name()
1085    }
1086
1087    /// Returns the motherboard version.
1088    ///
1089    /// This corresponds to the version or model number assigned by the motherboard's
1090    /// manufacturer (e.g. "0B98401 Pro").
1091    /// This information isn't available on ARM-based macOS systems.
1092    ///
1093    /// **Important**: this information is computed every time this function is called.
1094    ///
1095    /// ```no_run
1096    /// use sysinfo::Motherboard;
1097    ///
1098    /// if let Ok(m) = Motherboard::new() {
1099    ///     println!("Motherboard version: {:?}", m.version());
1100    /// }
1101    /// ```
1102    pub fn version(&self) -> Option<String> {
1103        self.inner.version()
1104    }
1105
1106    /// Returns the motherboard serial number.
1107    ///
1108    /// This corresponds to the serial number assigned by the motherboard's
1109    /// manufacturer (e.g. "W1KS427111E").
1110    ///
1111    /// **Important**: this information is computed every time this function is called.
1112    ///
1113    /// ```no_run
1114    /// use sysinfo::Motherboard;
1115    ///
1116    /// if let Ok(m) = Motherboard::new() {
1117    ///     println!("Motherboard serial number: {:?}", m.serial_number());
1118    /// }
1119    /// ```
1120    pub fn serial_number(&self) -> Option<String> {
1121        self.inner.serial_number()
1122    }
1123
1124    /// Returns the motherboard asset tag.
1125    ///
1126    /// This corresponds to the identifier assigned by the motherboard's
1127    /// manufacturer to track the physical device for inventory purposes.
1128    ///
1129    /// **Important**: this information is computed every time this function is called.
1130    ///
1131    /// ⚠️ Not supported on macOS/iOS.
1132    ///
1133    /// ```no_run
1134    /// use sysinfo::Motherboard;
1135    ///
1136    /// if let Ok(m) = Motherboard::new() {
1137    ///     println!("Motherboard asset tag: {:?}", m.asset_tag());
1138    /// }
1139    /// ```
1140    pub fn asset_tag(&self) -> Option<String> {
1141        self.inner.asset_tag()
1142    }
1143}
1144
1145/// This type allows to retrieve product-related information.
1146///
1147/// ⚠️ Not implemented on NetBSD.
1148///
1149/// ```
1150/// use sysinfo::Product;
1151///
1152/// println!("{:?}", Product);
1153/// ```
1154pub struct Product;
1155
1156impl Product {
1157    /// Returns the product name.
1158    ///
1159    /// This corresponds to the product name assigned by the hardware
1160    /// manufacturer (e.g. "20AN").
1161    ///
1162    /// **Important**: this information is computed every time this function is called.
1163    ///
1164    /// ```no_run
1165    /// use sysinfo::Product;
1166    ///
1167    /// println!("Product name: {:?}", Product::name());
1168    /// ```
1169    pub fn name() -> Result<String, Error> {
1170        ProductInner::name()
1171    }
1172
1173    /// Returns the product family identifier.
1174    ///
1175    /// This corresponds to the product family assigned by the hardware
1176    /// manufacturer (e.g. "T440p").
1177    ///
1178    /// **Important**: this information is computed every time this function is called.
1179    ///
1180    /// ```no_run
1181    /// use sysinfo::Product;
1182    ///
1183    /// println!("Product family: {:?}", Product::family());
1184    /// ```
1185    pub fn family() -> Result<String, Error> {
1186        ProductInner::family()
1187    }
1188
1189    /// Returns the product serial number.
1190    ///
1191    /// This corresponds to the serial identifier assigned by the hardware
1192    /// manufacturer (e.g. "W1KS427111E").
1193    ///
1194    /// **Important**: this information is computed every time this function is called.
1195    ///
1196    /// ```no_run
1197    /// use sysinfo::Product;
1198    ///
1199    /// println!("Product serial: {:?}", Product::serial_number());
1200    /// ```
1201    pub fn serial_number() -> Result<String, Error> {
1202        ProductInner::serial_number()
1203    }
1204
1205    /// Returns the product Stock Keeping Unit (SKU).
1206    ///
1207    /// This corresponds to the Stock Keeping Unit assigned by the hardware
1208    /// manufacturer (e.g. "LENOVO_MT_20AN") which identifies a specific
1209    /// model or configuration.
1210    ///
1211    /// **Important**: this information is computed every time this function is called.
1212    ///
1213    /// ⚠️ Not supported on macOS/iOS.
1214    ///
1215    /// ```no_run
1216    /// use sysinfo::Product;
1217    ///
1218    /// println!("Product sku: {:?}", Product::stock_keeping_unit());
1219    /// ```
1220    #[doc(alias = "sku")]
1221    pub fn stock_keeping_unit() -> Result<String, Error> {
1222        ProductInner::stock_keeping_unit()
1223    }
1224
1225    /// Returns the product UUID.
1226    ///
1227    /// This corresponds to the unique identifier assigned by the hardware
1228    /// manufacturer (e.g. "407488fe-960a-43b5-a265-8fd0e9200b8f") which uniquely
1229    /// identifies the physical system.
1230    ///
1231    /// **Important**: this information is computed every time this function is called.
1232    ///
1233    /// ```no_run
1234    /// use sysinfo::Product;
1235    ///
1236    /// println!("Product UUID: {:?}", Product::uuid());
1237    /// ```
1238    pub fn uuid() -> Result<String, Error> {
1239        ProductInner::uuid()
1240    }
1241
1242    /// Returns the product version.
1243    ///
1244    /// This corresponds to the version assigned by the hardware
1245    /// manufacturer (e.g. "Lenovo ThinkPad T440p") which identifies
1246    /// the specific version or revision of the product.
1247    ///
1248    /// **Important**: this information is computed every time this function is called.
1249    ///
1250    /// ```no_run
1251    /// use sysinfo::Product;
1252    ///
1253    /// println!("Product version: {:?}", Product::version());
1254    /// ```
1255    pub fn version() -> Result<String, Error> {
1256        ProductInner::version()
1257    }
1258
1259    /// Returns the product vendor name.
1260    ///
1261    /// This corresponds to the vendor name assigned by the hardware
1262    /// manufacturer (e.g. "LENOVO").
1263    ///
1264    /// **Important**: this information is computed every time this function is called.
1265    ///
1266    /// ```no_run
1267    /// use sysinfo::Product;
1268    ///
1269    /// println!("Vendor name: {:?}", Product::vendor_name());
1270    /// ```
1271    pub fn vendor_name() -> Result<String, Error> {
1272        ProductInner::vendor_name()
1273    }
1274}
1275
1276/// A struct representing system load average value.
1277///
1278/// It is returned by [`System::load_average`][crate::System::load_average].
1279///
1280/// ```no_run
1281/// use sysinfo::System;
1282///
1283/// match System::load_average() {
1284///     Ok(load_avg) => {
1285///         println!(
1286///             "one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
1287///             load_avg.one,
1288///             load_avg.five,
1289///             load_avg.fifteen,
1290///         );
1291///     }
1292///     Err(error) => eprintln!("Failed to get `load_average`: {error}"),
1293/// }
1294/// ```
1295#[repr(C)]
1296#[derive(Default, Debug, Clone)]
1297pub struct LoadAvg {
1298    /// Average load within one minute.
1299    pub one: f64,
1300    /// Average load within five minutes.
1301    pub five: f64,
1302    /// Average load within fifteen minutes.
1303    pub fifteen: f64,
1304}
1305
1306/// An enum representing signals on UNIX-like systems.
1307///
1308/// On non-unix systems, this enum is mostly useless and is only there to keep coherency between
1309/// the different OSes.
1310///
1311/// If you want the list of the supported signals on the current system, use
1312/// [`SUPPORTED_SIGNALS`][crate::SUPPORTED_SIGNALS].
1313#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
1314#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
1315pub enum Signal {
1316    /// Hangup detected on controlling terminal or death of controlling process.
1317    Hangup,
1318    /// Interrupt from keyboard.
1319    Interrupt,
1320    /// Quit from keyboard.
1321    Quit,
1322    /// Illegal instruction.
1323    Illegal,
1324    /// Trace/breakpoint trap.
1325    Trap,
1326    /// Abort signal from C abort function.
1327    Abort,
1328    /// IOT trap. A synonym for SIGABRT.
1329    IOT,
1330    /// Bus error (bad memory access).
1331    Bus,
1332    /// Floating point exception.
1333    FloatingPointException,
1334    /// Kill signal.
1335    Kill,
1336    /// User-defined signal 1.
1337    User1,
1338    /// Invalid memory reference.
1339    Segv,
1340    /// User-defined signal 2.
1341    User2,
1342    /// Broken pipe: write to pipe with no readers.
1343    Pipe,
1344    /// Timer signal from C alarm function.
1345    Alarm,
1346    /// Termination signal.
1347    Term,
1348    /// Child stopped or terminated.
1349    Child,
1350    /// Continue if stopped.
1351    Continue,
1352    /// Stop process.
1353    Stop,
1354    /// Stop typed at terminal.
1355    TSTP,
1356    /// Terminal input for background process.
1357    TTIN,
1358    /// Terminal output for background process.
1359    TTOU,
1360    /// Urgent condition on socket.
1361    Urgent,
1362    /// CPU time limit exceeded.
1363    XCPU,
1364    /// File size limit exceeded.
1365    XFSZ,
1366    /// Virtual alarm clock.
1367    VirtualAlarm,
1368    /// Profiling time expired.
1369    Profiling,
1370    /// Windows resize signal.
1371    Winch,
1372    /// I/O now possible.
1373    IO,
1374    /// Pollable event (Sys V). Synonym for IO
1375    Poll,
1376    /// Power failure (System V).
1377    ///
1378    /// Doesn't exist on apple systems so will be ignored.
1379    Power,
1380    /// Bad argument to routine (SVr4).
1381    Sys,
1382}
1383
1384impl std::fmt::Display for Signal {
1385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1386        let s = match *self {
1387            Self::Hangup => "Hangup",
1388            Self::Interrupt => "Interrupt",
1389            Self::Quit => "Quit",
1390            Self::Illegal => "Illegal",
1391            Self::Trap => "Trap",
1392            Self::Abort => "Abort",
1393            Self::IOT => "IOT",
1394            Self::Bus => "Bus",
1395            Self::FloatingPointException => "FloatingPointException",
1396            Self::Kill => "Kill",
1397            Self::User1 => "User1",
1398            Self::Segv => "Segv",
1399            Self::User2 => "User2",
1400            Self::Pipe => "Pipe",
1401            Self::Alarm => "Alarm",
1402            Self::Term => "Term",
1403            Self::Child => "Child",
1404            Self::Continue => "Continue",
1405            Self::Stop => "Stop",
1406            Self::TSTP => "TSTP",
1407            Self::TTIN => "TTIN",
1408            Self::TTOU => "TTOU",
1409            Self::Urgent => "Urgent",
1410            Self::XCPU => "XCPU",
1411            Self::XFSZ => "XFSZ",
1412            Self::VirtualAlarm => "VirtualAlarm",
1413            Self::Profiling => "Profiling",
1414            Self::Winch => "Winch",
1415            Self::IO => "IO",
1416            Self::Poll => "Poll",
1417            Self::Power => "Power",
1418            Self::Sys => "Sys",
1419        };
1420        f.write_str(s)
1421    }
1422}
1423
1424/// Contains memory limits for a cgroup.
1425#[derive(Default, Debug, Clone)]
1426pub struct CGroupLimits {
1427    /// Total memory (in bytes) for the cgroup.
1428    pub total_memory: u64,
1429    /// Free memory (in bytes) for the cgroup.
1430    pub free_memory: u64,
1431    /// Free swap (in bytes) for the cgroup.
1432    pub free_swap: u64,
1433    /// Resident Set Size (RSS) (in bytes) for the cgroup.
1434    pub rss: u64,
1435}
1436
1437/// Enum describing the different status of a process.
1438#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
1439#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
1440pub enum ProcessStatus {
1441    /// ## Linux
1442    ///
1443    /// Idle kernel thread.
1444    ///
1445    /// ## macOs/FreeBSD
1446    ///
1447    /// Process being created by fork.
1448    ///
1449    /// ## Other OS
1450    ///
1451    /// Not available.
1452    Idle,
1453    /// Running.
1454    Run,
1455    /// ## Linux
1456    ///
1457    /// Sleeping in an interruptible waiting.
1458    ///
1459    /// ## macOS/FreeBSD
1460    ///
1461    /// Sleeping on an address.
1462    ///
1463    /// ## Other OS
1464    ///
1465    /// Not available.
1466    Sleep,
1467    /// ## Linux
1468    ///
1469    /// Stopped (on a signal) or (before Linux 2.6.33) trace stopped.
1470    ///
1471    /// ## macOS/FreeBSD
1472    ///
1473    /// Process debugging or suspension.
1474    ///
1475    /// ## Other OS
1476    ///
1477    /// Not available.
1478    Stop,
1479    /// ## Linux/FreeBSD/macOS
1480    ///
1481    /// Zombie process. Terminated but not reaped by its parent.
1482    ///
1483    /// ## Other OS
1484    ///
1485    /// Not available.
1486    Zombie,
1487    /// ## Linux
1488    ///
1489    /// Tracing stop (Linux 2.6.33 onward). Stopped by debugger during the tracing.
1490    ///
1491    /// ## NetBSD
1492    ///
1493    /// The process is being traced or debugged.
1494    ///
1495    /// ## Other OS
1496    ///
1497    /// Not available.
1498    Tracing,
1499    /// ## Linux
1500    ///
1501    /// Dead/uninterruptible sleep (usually IO).
1502    ///
1503    /// ## FreeBSD
1504    ///
1505    /// A process should never end up in this state.
1506    ///
1507    /// ## Other OS
1508    ///
1509    /// Not available.
1510    Dead,
1511    /// ## Linux
1512    ///
1513    /// Wakekill (Linux 2.6.33 to 3.13 only).
1514    ///
1515    /// ## Other OS
1516    ///
1517    /// Not available.
1518    Wakekill,
1519    /// ## Linux
1520    ///
1521    /// Waking (Linux 2.6.33 to 3.13 only).
1522    ///
1523    /// ## Other OS
1524    ///
1525    /// Not available.
1526    Waking,
1527    /// ## Linux
1528    ///
1529    /// Parked (Linux 3.9 to 3.13 only).
1530    ///
1531    /// ## macOS
1532    ///
1533    /// Halted at a clean point.
1534    ///
1535    /// ## Other OS
1536    ///
1537    /// Not available.
1538    Parked,
1539    /// ## FreeBSD
1540    ///
1541    /// Blocked on a lock.
1542    ///
1543    /// ## Other OS
1544    ///
1545    /// Not available.
1546    LockBlocked,
1547    /// ## Linux
1548    ///
1549    /// Waiting in uninterruptible disk sleep.
1550    ///
1551    /// ## Other OS
1552    ///
1553    /// Not available.
1554    UninterruptibleDiskSleep,
1555    /// ## NetBSD
1556    ///
1557    /// Suspended process.
1558    ///
1559    /// ## Other OS
1560    ///
1561    /// Not available.
1562    Suspended,
1563    /// Unknown.
1564    Unknown(u32),
1565}
1566
1567/// Enum describing the different kind of threads.
1568#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1569#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
1570pub enum ThreadKind {
1571    /// Kernel thread.
1572    Kernel,
1573    /// User thread.
1574    Userland,
1575}
1576
1577/// Enum describing possible [`Process::kill_and_wait`] errors.
1578#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1579#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
1580pub enum KillError {
1581    /// This signal doesn't exist on this platform.
1582    SignalDoesNotExist,
1583    /// The signal failed to be sent to the target process.
1584    FailedToSendSignal,
1585}
1586
1587impl core::fmt::Display for KillError {
1588    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1589        match self {
1590            Self::SignalDoesNotExist => f.write_str("signal does not exist"),
1591            Self::FailedToSendSignal => f.write_str("failed to send signal"),
1592        }
1593    }
1594}
1595
1596impl core::error::Error for KillError {}
1597
1598/// Struct containing information of a process.
1599///
1600/// ## iOS
1601///
1602/// This information cannot be retrieved on iOS due to sandboxing.
1603///
1604/// ## Apple app store
1605///
1606/// If you are building a macOS Apple app store, it won't be able
1607/// to retrieve this information.
1608///
1609/// ```no_run
1610/// use sysinfo::{Pid, System};
1611///
1612/// if let Ok(s) = System::new_all()
1613///     && let Some(process) = s.process(Pid::from(1337))
1614/// {
1615///     println!("{:?}", process.name());
1616/// }
1617/// ```
1618pub struct Process {
1619    pub(crate) inner: ProcessInner,
1620}
1621
1622impl Process {
1623    /// Sends [`Signal::Kill`] to the process (which is the only signal supported on all supported
1624    /// platforms by this crate).
1625    ///
1626    /// Returns `true` if the signal was sent successfully. If you want to wait for this process
1627    /// to end, you can use [`Process::wait`] or directly [`Process::kill_and_wait`].
1628    ///
1629    /// ⚠️ Even if this function returns `true`, it doesn't necessarily mean that the process will
1630    /// be killed. It just means that the signal was sent successfully.
1631    ///
1632    /// ⚠️ Please note that some processes might not be "killable", like if they run with higher
1633    /// levels than the current process for example.
1634    ///
1635    /// If you want to use another signal, take a look at [`Process::kill_with`].
1636    ///
1637    /// To get the list of the supported signals on this system, use
1638    /// [`SUPPORTED_SIGNALS`][crate::SUPPORTED_SIGNALS].
1639    ///
1640    /// ```no_run
1641    /// use sysinfo::{Pid, System};
1642    ///
1643    /// if let Ok(s) = System::new_all()
1644    ///     && let Some(process) = s.process(Pid::from(1337))
1645    /// {
1646    ///     process.kill();
1647    /// }
1648    /// ```
1649    pub fn kill(&self) -> bool {
1650        self.kill_with(Signal::Kill).unwrap_or(false)
1651    }
1652
1653    /// Sends the given `signal` to the process. If the signal doesn't exist on this platform,
1654    /// it'll do nothing and will return `None`. Otherwise it'll return `Some(bool)`. The boolean
1655    /// value will depend on whether or not the signal was sent successfully.
1656    ///
1657    /// If you just want to kill the process, use [`Process::kill`] directly. If you want to wait
1658    /// for this process to end, you can use [`Process::wait`] or [`Process::kill_with_and_wait`].
1659    ///
1660    /// ⚠️ Please note that some processes might not be "killable", like if they run with higher
1661    /// levels than the current process for example.
1662    ///
1663    /// To get the list of the supported signals on this system, use
1664    /// [`SUPPORTED_SIGNALS`][crate::SUPPORTED_SIGNALS].
1665    ///
1666    /// ```no_run
1667    /// use sysinfo::{Pid, Signal, System};
1668    ///
1669    /// if let Ok(s) = System::new_all()
1670    ///     && let Some(process) = s.process(Pid::from(1337))
1671    /// {
1672    ///     println!("Trying to send `kill` signal to {}", process.pid());
1673    ///     if process.kill_with(Signal::Kill).is_none() {
1674    ///         println!("This signal isn't supported on this platform");
1675    ///     }
1676    /// }
1677    /// ```
1678    pub fn kill_with(&self, signal: Signal) -> Option<bool> {
1679        self.inner.kill_with(signal)
1680    }
1681
1682    /// Sends [`Signal::Kill`] to the process then waits for its termination.
1683    ///
1684    /// Internally, this method is calling [`Process::kill`] then [`Process::wait`].
1685    ///
1686    /// ⚠️ Please note that some processes might not be "killable", like if they run with higher
1687    /// levels than the current process for example. In this case, this method could enter an
1688    /// infinite loop.
1689    ///
1690    /// ```no_run
1691    /// use sysinfo::{Pid, System};
1692    ///
1693    /// if let Ok(s) = System::new_all()
1694    ///     && let Some(process) = s.process(Pid::from(1337))
1695    /// {
1696    ///     println!("Trying to kill and wait for process {}", process.pid());
1697    ///     if let Err(error) = process.kill_and_wait() {
1698    ///         println!("`kill_and_wait` failed: {error:?}");
1699    ///     }
1700    /// }
1701    /// ```
1702    pub fn kill_and_wait(&self) -> Result<Option<ExitStatus>, KillError> {
1703        self.kill_with_and_wait(Signal::Kill)
1704    }
1705
1706    /// Sends the given `signal` to the process.then waits for its termination.
1707    ///
1708    /// Internally, this method is calling [`Process::kill_with`] then [`Process::wait`].
1709    ///
1710    /// ⚠️ Please note that some processes might not be "killable", like if they run with higher
1711    /// levels than the current process for example. In this case, this method could enter an
1712    /// infinite loop.
1713    ///
1714    /// To get the list of the supported signals on this system, use
1715    /// [`SUPPORTED_SIGNALS`][crate::SUPPORTED_SIGNALS].
1716    ///
1717    /// ```no_run
1718    /// use sysinfo::{Pid, System};
1719    ///
1720    /// if let Ok(s) = System::new_all()
1721    ///     && let Some(process) = s.process(Pid::from(1337))
1722    /// {
1723    ///     println!("Trying to kill and wait process {}", process.pid());
1724    ///     if let Err(error) = process.kill_and_wait() {
1725    ///         println!("`kill_and_wait` failed: {error:?}");
1726    ///     }
1727    /// }
1728    /// ```
1729    pub fn kill_with_and_wait(&self, signal: Signal) -> Result<Option<ExitStatus>, KillError> {
1730        match self.inner.kill_with(signal) {
1731            Some(sent) => {
1732                if !sent {
1733                    return Err(KillError::FailedToSendSignal);
1734                }
1735            }
1736            None => return Err(KillError::SignalDoesNotExist),
1737        }
1738
1739        Ok(self.inner.wait())
1740    }
1741
1742    /// Waits for process termination and returns its [`ExitStatus`] if it could be retrieved,
1743    /// returns `None` otherwise. It means that as long as the process is alive, this method will
1744    /// not return.
1745    ///
1746    /// ⚠️ On **macOS** and **FreeBSD**, if the process died and a new one took its PID, unless
1747    /// you refreshed, it will wait for the new process to end.
1748    ///
1749    /// On **Windows**, as long as we have a (internal) handle, we can always retrieve the exit
1750    /// status.
1751    ///
1752    /// On **Linux**/**Android**, we check that the start time of the PID we're waiting is the same
1753    /// as the current process'. If not it means the process died and a new one got its PID.
1754    ///
1755    /// ```no_run
1756    /// use sysinfo::{Pid, System};
1757    ///
1758    /// if let Ok(mut s) = System::new_all() {
1759    ///     println!("Looking for process 1337");
1760    ///     if let Some(process) = s.process(Pid::from(1337)) {
1761    ///         println!("Waiting for pid 1337");
1762    ///         let exit_status = process.wait();
1763    ///         println!("Pid 1337 exited with: {exit_status:?}");
1764    ///     }
1765    /// }
1766    /// ```
1767    pub fn wait(&self) -> Option<ExitStatus> {
1768        self.inner.wait()
1769    }
1770
1771    /// Returns the name of the process.
1772    ///
1773    /// **⚠️ Important ⚠️**
1774    ///
1775    /// On **Linux**, there are two things to know about processes' name:
1776    ///  1. It is limited to 15 characters.
1777    ///  2. It is not always the exe name.
1778    ///
1779    /// If you are looking for a specific process, unless you know what you are
1780    /// doing, in most cases it's better to use [`Process::exe`] instead (which
1781    /// can be empty sometimes!).
1782    ///
1783    /// ```no_run
1784    /// use sysinfo::{Pid, System};
1785    ///
1786    /// if let Ok(s) = System::new_all()
1787    ///     && let Some(process) = s.process(Pid::from(1337))
1788    /// {
1789    ///     println!("{:?}", process.name());
1790    /// }
1791    /// ```
1792    pub fn name(&self) -> &OsStr {
1793        self.inner.name()
1794    }
1795
1796    /// Returns the command line.
1797    ///
1798    ///  **⚠️ Important ⚠️**
1799    ///
1800    /// On **Windows**, you might need to use `administrator` privileges when running your program
1801    /// to have access to this information.
1802    ///
1803    /// ```no_run
1804    /// use sysinfo::{Pid, System};
1805    ///
1806    /// if let Ok(s) = System::new_all()
1807    ///     && let Some(process) = s.process(Pid::from(1337))
1808    /// {
1809    ///     println!("{:?}", process.cmd());
1810    /// }
1811    /// ```
1812    pub fn cmd(&self) -> &[OsString] {
1813        self.inner.cmd()
1814    }
1815
1816    /// Returns the path to the process.
1817    ///
1818    /// ```no_run
1819    /// use sysinfo::{Pid, System};
1820    ///
1821    /// if let Ok(s) = System::new_all()
1822    ///     && let Some(process) = s.process(Pid::from(1337))
1823    /// {
1824    ///     println!("{:?}", process.exe());
1825    /// }
1826    /// ```
1827    ///
1828    /// ### Implementation notes
1829    ///
1830    /// On Linux, this method will return an empty path if there
1831    /// was an error trying to read `/proc/<pid>/exe`. This can
1832    /// happen, for example, if the permission levels or UID namespaces
1833    /// between the caller and target processes are different.
1834    ///
1835    /// It is also the case that `cmd[0]` is _not_ usually a correct
1836    /// replacement for this.
1837    /// A process [may change its `cmd[0]` value](https://man7.org/linux/man-pages/man5/proc.5.html)
1838    /// freely, making this an untrustworthy source of information.
1839    pub fn exe(&self) -> Option<&Path> {
1840        self.inner.exe()
1841    }
1842
1843    /// Returns the PID of the process.
1844    ///
1845    /// ```no_run
1846    /// use sysinfo::{Pid, System};
1847    ///
1848    /// if let Ok(s) = System::new_all()
1849    ///     && let Some(process) = s.process(Pid::from(1337))
1850    /// {
1851    ///     println!("{}", process.pid());
1852    /// }
1853    /// ```
1854    pub fn pid(&self) -> Pid {
1855        self.inner.pid()
1856    }
1857
1858    /// Retrieves the limits for the process cgroup (if any), otherwise it returns `None`.
1859    ///
1860    /// This information is computed every time the method is called.
1861    ///
1862    /// ⚠️ This method is only implemented for Linux. It always returns `None` for all other
1863    /// systems.
1864    ///
1865    /// ```no_run
1866    /// use sysinfo::{Pid, System};
1867    ///
1868    /// if let Ok(s) = System::new_all()
1869    ///     && let Some(process) = s.process(Pid::from(1337))
1870    /// {
1871    ///     println!("limits: {:?}", process.cgroup_limits());
1872    /// }
1873    /// ```
1874    pub fn cgroup_limits(&self) -> Option<CGroupLimits> {
1875        self.inner.cgroup_limits()
1876    }
1877
1878    /// Returns the environment variables of the process.
1879    ///
1880    /// ```no_run
1881    /// use sysinfo::{Pid, System};
1882    ///
1883    /// if let Ok(s) = System::new_all()
1884    ///     && let Some(process) = s.process(Pid::from(1337))
1885    /// {
1886    ///     println!("{:?}", process.environ());
1887    /// }
1888    /// ```
1889    pub fn environ(&self) -> &[OsString] {
1890        self.inner.environ()
1891    }
1892
1893    /// Returns the current working directory.
1894    ///
1895    /// ```no_run
1896    /// use sysinfo::{Pid, System};
1897    ///
1898    /// if let Ok(s) = System::new_all()
1899    ///     && let Some(process) = s.process(Pid::from(1337))
1900    /// {
1901    ///     println!("{:?}", process.cwd());
1902    /// }
1903    /// ```
1904    pub fn cwd(&self) -> Option<&Path> {
1905        self.inner.cwd()
1906    }
1907
1908    /// Returns the path of the root directory.
1909    ///
1910    /// ⚠️ Not implemented in NetBSD.
1911    ///
1912    /// ```no_run
1913    /// use sysinfo::{Pid, System};
1914    ///
1915    /// if let Ok(s) = System::new_all()
1916    ///     && let Some(process) = s.process(Pid::from(1337))
1917    /// {
1918    ///     println!("{:?}", process.root());
1919    /// }
1920    /// ```
1921    pub fn root(&self) -> Option<&Path> {
1922        self.inner.root()
1923    }
1924
1925    /// Returns the memory usage (in bytes).
1926    ///
1927    /// This method returns the [size of the resident set], that is, the amount of memory that the
1928    /// process allocated and which is currently mapped in physical RAM. It does not include memory
1929    /// that is swapped out, or, in some operating systems, that has been allocated but never used.
1930    ///
1931    /// Thus, it represents exactly the amount of physical RAM that the process is using at the
1932    /// present time, but it might not be a good indicator of the total memory that the process will
1933    /// be using over its lifetime. For that purpose, you can try and use
1934    /// [`virtual_memory`](Process::virtual_memory).
1935    ///
1936    /// ```no_run
1937    /// use sysinfo::{Pid, System};
1938    ///
1939    /// if let Ok(s) = System::new_all()
1940    ///     && let Some(process) = s.process(Pid::from(1337))
1941    /// {
1942    ///     println!("{} bytes", process.memory());
1943    /// }
1944    /// ```
1945    ///
1946    /// [size of the resident set]: https://en.wikipedia.org/wiki/Resident_set_size
1947    pub fn memory(&self) -> u64 {
1948        self.inner.memory()
1949    }
1950
1951    /// Returns the virtual memory usage (in bytes).
1952    ///
1953    /// This method returns the [size of virtual memory], that is, the amount of memory that the
1954    /// process can access, whether it is currently mapped in physical RAM or not. It includes
1955    /// physical RAM, allocated but not used regions, swapped-out regions, and even memory
1956    /// associated with [memory-mapped files](https://en.wikipedia.org/wiki/Memory-mapped_file).
1957    ///
1958    /// This value has limitations though. Depending on the operating system and type of process,
1959    /// this value might be a good indicator of the total memory that the process will be using over
1960    /// its lifetime. However, for example, in the version 14 of macOS this value is in the order of
1961    /// the hundreds of gigabytes for every process, and thus not very informative. Moreover, if a
1962    /// process maps into memory a very large file, this value will increase accordingly, even if
1963    /// the process is not actively using the memory.
1964    ///
1965    /// ```no_run
1966    /// use sysinfo::{Pid, System};
1967    ///
1968    /// if let Ok(s) = System::new_all()
1969    ///     && let Some(process) = s.process(Pid::from(1337))
1970    /// {
1971    ///     println!("{} bytes", process.virtual_memory());
1972    /// }
1973    /// ```
1974    ///
1975    /// [size of virtual memory]: https://en.wikipedia.org/wiki/Virtual_memory
1976    pub fn virtual_memory(&self) -> u64 {
1977        self.inner.virtual_memory()
1978    }
1979
1980    /// Returns the parent PID.
1981    ///
1982    /// ```no_run
1983    /// use sysinfo::{Pid, System};
1984    ///
1985    /// if let Ok(s) = System::new_all()
1986    ///     && let Some(process) = s.process(Pid::from(1337))
1987    /// {
1988    ///     println!("{:?}", process.parent());
1989    /// }
1990    /// ```
1991    pub fn parent(&self) -> Option<Pid> {
1992        self.inner.parent()
1993    }
1994
1995    /// Returns the status of the process.
1996    ///
1997    /// ```no_run
1998    /// use sysinfo::{Pid, System};
1999    ///
2000    /// if let Ok(s) = System::new_all()
2001    ///     && let Some(process) = s.process(Pid::from(1337))
2002    /// {
2003    ///     println!("{:?}", process.status());
2004    /// }
2005    /// ```
2006    pub fn status(&self) -> ProcessStatus {
2007        self.inner.status()
2008    }
2009
2010    /// Returns the time where the process was started (in seconds) from epoch.
2011    ///
2012    /// ```no_run
2013    /// use sysinfo::{Pid, System};
2014    ///
2015    /// if let Ok(s) = System::new_all()
2016    ///     && let Some(process) = s.process(Pid::from(1337))
2017    /// {
2018    ///     println!("Started at {} seconds", process.start_time());
2019    /// }
2020    /// ```
2021    pub fn start_time(&self) -> u64 {
2022        self.inner.start_time()
2023    }
2024
2025    /// Returns for how much time the process has been running (in seconds).
2026    ///
2027    /// ```no_run
2028    /// use sysinfo::{Pid, System};
2029    ///
2030    /// if let Ok(s) = System::new_all()
2031    ///     && let Some(process) = s.process(Pid::from(1337))
2032    /// {
2033    ///     println!("Running since {} seconds", process.run_time());
2034    /// }
2035    /// ```
2036    pub fn run_time(&self) -> u64 {
2037        self.inner.run_time()
2038    }
2039
2040    /// Returns the total CPU usage (in %). Notice that it might be bigger than
2041    /// 100 if run on a multi-core machine.
2042    ///
2043    /// If you want a value between 0% and 100%, divide the returned value by
2044    /// the number of CPUs.
2045    ///
2046    /// ⚠️ To start to have accurate CPU usage, a process needs to be refreshed
2047    /// **twice** because CPU usage computation is based on time diff (process
2048    /// time on a given time period divided by total system time on the same
2049    /// time period).
2050    ///
2051    /// ⚠️ If you want accurate CPU usage number, better leave a bit of time
2052    /// between two calls of this method (take a look at
2053    /// [`MINIMUM_CPU_UPDATE_INTERVAL`][crate::MINIMUM_CPU_UPDATE_INTERVAL] for
2054    /// more information).
2055    ///
2056    /// ```no_run
2057    /// use sysinfo::{Pid, ProcessesToUpdate, ProcessRefreshKind, System};
2058    ///
2059    /// if let Ok(mut s) = System::new_all() {
2060    ///     // Wait a bit because CPU usage is based on diff.
2061    ///     std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
2062    ///     // Refresh CPU usage to get actual value.
2063    ///     s.refresh_processes_specifics(
2064    ///         ProcessesToUpdate::All,
2065    ///         true,
2066    ///         ProcessRefreshKind::nothing().with_cpu()
2067    ///     );
2068    ///     if let Some(process) = s.process(Pid::from(1337)) {
2069    ///         println!("{}%", process.cpu_usage());
2070    ///     }
2071    /// }
2072    /// ```
2073    pub fn cpu_usage(&self) -> f32 {
2074        self.inner.cpu_usage()
2075    }
2076
2077    /// Returns the total accumulated CPU usage (in CPU-milliseconds). Note
2078    /// that it might be bigger than the total clock run time of a process if
2079    /// run on a multi-core machine.
2080    ///
2081    /// ```no_run
2082    /// use sysinfo::{Pid, System};
2083    ///
2084    /// if let Ok(s) = System::new_all()
2085    ///     && let Some(process) = s.process(Pid::from(1337))
2086    /// {
2087    ///     println!("{}", process.accumulated_cpu_time());
2088    /// }
2089    /// ```
2090    pub fn accumulated_cpu_time(&self) -> u64 {
2091        self.inner.accumulated_cpu_time()
2092    }
2093
2094    /// Returns number of bytes read and written to disk.
2095    ///
2096    /// ⚠️ On Windows, this method actually returns **ALL** I/O read and
2097    /// written bytes.
2098    ///
2099    /// ⚠️ Files might be cached in memory by your OS, meaning that reading/writing them might not
2100    /// increase the `read_bytes`/`written_bytes` values. You can find more information about it
2101    /// in the `proc_pid_io` manual (`man proc_pid_io` on unix platforms).
2102    ///
2103    /// ```no_run
2104    /// use sysinfo::{Pid, System};
2105    ///
2106    /// if let Ok(s) = System::new_all()
2107    ///     && let Some(process) = s.process(Pid::from(1337))
2108    /// {
2109    ///     let disk_usage = process.disk_usage();
2110    ///     println!("read bytes   : new/total => {}/{}",
2111    ///         disk_usage.read_bytes,
2112    ///         disk_usage.total_read_bytes,
2113    ///     );
2114    ///     println!("written bytes: new/total => {}/{}",
2115    ///         disk_usage.written_bytes,
2116    ///         disk_usage.total_written_bytes,
2117    ///     );
2118    /// }
2119    /// ```
2120    pub fn disk_usage(&self) -> DiskUsage {
2121        self.inner.disk_usage()
2122    }
2123
2124    /// Returns the ID of the owner user of this process or `None` if this
2125    /// information couldn't be retrieved. If you want to get the [`User`] from
2126    /// it, take a look at [`Users::get_user_by_id`].
2127    ///
2128    /// [`User`]: crate::User
2129    /// [`Users::get_user_by_id`]: crate::Users::get_user_by_id
2130    ///
2131    /// ```no_run
2132    /// use sysinfo::{Pid, System};
2133    ///
2134    /// if let Ok(mut s) = System::new_all()
2135    ///     && let Some(process) = s.process(Pid::from(1337))
2136    /// {
2137    ///     println!("User id for process 1337: {:?}", process.user_id());
2138    /// }
2139    /// ```
2140    pub fn user_id(&self) -> Option<&Uid> {
2141        self.inner.user_id()
2142    }
2143
2144    /// Returns the user ID of the effective owner of this process or `None` if
2145    /// this information couldn't be retrieved. If you want to get the [`User`]
2146    /// from it, take a look at [`Users::get_user_by_id`].
2147    ///
2148    /// If you run something with `sudo`, the real user ID of the launched
2149    /// process will be the ID of the user you are logged in as but effective
2150    /// user ID will be `0` (i-e root).
2151    ///
2152    /// ⚠️ It always returns `None` on Windows.
2153    ///
2154    /// [`User`]: crate::User
2155    /// [`Users::get_user_by_id`]: crate::Users::get_user_by_id
2156    ///
2157    /// ```no_run
2158    /// use sysinfo::{Pid, System};
2159    ///
2160    /// if let Ok(mut s) = System::new_all()
2161    ///     && let Some(process) = s.process(Pid::from(1337))
2162    /// {
2163    ///     println!("User id for process 1337: {:?}", process.effective_user_id());
2164    /// }
2165    /// ```
2166    pub fn effective_user_id(&self) -> Option<&Uid> {
2167        self.inner.effective_user_id()
2168    }
2169
2170    /// Returns the process group ID of the process.
2171    ///
2172    /// ⚠️ It always returns `None` on Windows.
2173    ///
2174    /// ```no_run
2175    /// use sysinfo::{Pid, System};
2176    ///
2177    /// if let Ok(mut s) = System::new_all()
2178    ///     && let Some(process) = s.process(Pid::from(1337))
2179    /// {
2180    ///     println!("Group ID for process 1337: {:?}", process.group_id());
2181    /// }
2182    /// ```
2183    pub fn group_id(&self) -> Option<Gid> {
2184        self.inner.group_id()
2185    }
2186
2187    /// Returns the effective group ID of the process.
2188    ///
2189    /// If you run something with `sudo`, the real group ID of the launched
2190    /// process will be the primary group ID you are logged in as but effective
2191    /// group ID will be `0` (i-e root).
2192    ///
2193    /// ⚠️ It always returns `None` on Windows.
2194    ///
2195    /// ```no_run
2196    /// use sysinfo::{Pid, System};
2197    ///
2198    /// if let Ok(mut s) = System::new_all()
2199    ///     && let Some(process) = s.process(Pid::from(1337))
2200    /// {
2201    ///     println!("User id for process 1337: {:?}", process.effective_group_id());
2202    /// }
2203    /// ```
2204    pub fn effective_group_id(&self) -> Option<Gid> {
2205        self.inner.effective_group_id()
2206    }
2207
2208    /// Returns the session ID for the current process or `None` if it couldn't
2209    /// be retrieved.
2210    ///
2211    /// ⚠️ This information is computed every time this method is called.
2212    ///
2213    /// ```no_run
2214    /// use sysinfo::{Pid, System};
2215    ///
2216    /// if let Ok(mut s) = System::new_all()
2217    ///     && let Some(process) = s.process(Pid::from(1337))
2218    /// {
2219    ///     println!("Session ID for process 1337: {:?}", process.session_id());
2220    /// }
2221    /// ```
2222    pub fn session_id(&self) -> Option<Pid> {
2223        self.inner.session_id()
2224    }
2225
2226    /// Tasks run by this process. If there are none, returns `None`.
2227    ///
2228    /// ⚠️ This method always returns `None` on other platforms than Linux.
2229    ///
2230    /// ```no_run
2231    /// use sysinfo::{Pid, System};
2232    ///
2233    /// if let Ok(mut s) = System::new_all()
2234    ///     && let Some(process) = s.process(Pid::from(1337))
2235    /// {
2236    ///     if let Some(tasks) = process.tasks() {
2237    ///         println!("Listing tasks for process {:?}", process.pid());
2238    ///         for task_pid in tasks {
2239    ///             if let Some(task) = s.process(*task_pid) {
2240    ///                 println!("Task {:?}: {:?}", task.pid(), task.name());
2241    ///             }
2242    ///         }
2243    ///     }
2244    /// }
2245    /// ```
2246    pub fn tasks(&self) -> Option<&HashSet<Pid>> {
2247        cfg_select! {
2248            all(
2249                any(target_os = "linux", target_os = "android"),
2250                not(feature = "unknown-ci")
2251            ) => {
2252                self.inner.tasks.as_ref()
2253            }
2254            _ => {
2255                None
2256            }
2257        }
2258    }
2259
2260    /// If the process is a thread, it'll return `Some` with the kind of thread it is. Returns
2261    /// `None` otherwise.
2262    ///
2263    /// ⚠️ This method always returns `None` on other platforms than Linux.
2264    ///
2265    /// ```no_run
2266    /// use sysinfo::System;
2267    ///
2268    /// if let Ok(s) = System::new_all() {
2269    ///     for (_, process) in s.processes() {
2270    ///         if let Some(thread_kind) = process.thread_kind() {
2271    ///             println!("Process {:?} is a {thread_kind:?} thread", process.pid());
2272    ///         }
2273    ///     }
2274    /// }
2275    /// ```
2276    pub fn thread_kind(&self) -> Option<ThreadKind> {
2277        cfg_select! {
2278            all(
2279                any(target_os = "linux", target_os = "android"),
2280                not(feature = "unknown-ci")
2281            ) => self.inner.thread_kind(),
2282            _ => None,
2283        }
2284    }
2285
2286    /// Returns `true` if the process doesn't exist anymore but was not yet removed from
2287    /// the processes list because the `remove_dead_processes` argument was set to `false`
2288    /// in methods like [`System::refresh_processes`].
2289    ///
2290    /// ```no_run
2291    /// use sysinfo::{ProcessesToUpdate, System};
2292    ///
2293    /// if let Ok(mut s) = System::new_all() {
2294    ///     // We set the `remove_dead_processes` to `false`.
2295    ///     s.refresh_processes(ProcessesToUpdate::All, false);
2296    ///
2297    ///     for (_, process) in s.processes() {
2298    ///         println!(
2299    ///             "Process {:?} {}",
2300    ///             process.pid(),
2301    ///             if process.exists() { "exists" } else { "doesn't exist" },
2302    ///         );
2303    ///     }
2304    /// }
2305    /// ```
2306    pub fn exists(&self) -> bool {
2307        self.inner.exists()
2308    }
2309
2310    /// Returns the number of open files in the current process.
2311    ///
2312    /// Returns `None` if it failed retrieving the information or if the current system is not
2313    /// supported.
2314    ///
2315    /// **Important**: this information is computed every time this function is called.
2316    ///
2317    /// ⚠️ Not implemented on NetBSD.
2318    ///
2319    /// ```no_run
2320    /// use sysinfo::System;
2321    ///
2322    /// if let Ok(s) = System::new_all() {
2323    ///     for (_, process) in s.processes() {
2324    ///         println!(
2325    ///             "Process {:?} {:?}",
2326    ///             process.pid(),
2327    ///             process.open_files(),
2328    ///         );
2329    ///     }
2330    /// }
2331    /// ```
2332    pub fn open_files(&self) -> Option<usize> {
2333        self.inner.open_files()
2334    }
2335
2336    /// Returns the maximum number of open files for the current process.
2337    ///
2338    /// Returns `None` if it failed retrieving the information or if the current system is not
2339    /// supported.
2340    ///
2341    /// **Important**: this information is computed every time this function is called.
2342    ///
2343    /// ```no_run
2344    /// use sysinfo::System;
2345    ///
2346    /// if let Ok(s) = System::new_all() {
2347    ///     for (_, process) in s.processes() {
2348    ///         println!(
2349    ///             "Process {:?} {:?}",
2350    ///             process.pid(),
2351    ///             process.open_files_limit(),
2352    ///         );
2353    ///     }
2354    /// }
2355    /// ```
2356    pub fn open_files_limit(&self) -> Option<usize> {
2357        self.inner.open_files_limit()
2358    }
2359
2360    /// Returns the total % usage of all GPUs by this process.
2361    ///
2362    /// Returns `None` if it failed retrieving the information or if the current system is not
2363    /// supported.
2364    ///
2365    /// ```no_run
2366    /// use sysinfo::System;
2367    ///
2368    /// if let Ok(s) = System::new_all() {
2369    ///     for (_, process) in s.processes() {
2370    ///         println!(
2371    ///             "[Process {:?}] GPU usage: {:?}%",
2372    ///             process.pid(),
2373    ///             process.gpu_usage(),
2374    ///         );
2375    ///     }
2376    /// }
2377    /// ```
2378    #[cfg(feature = "gpu")]
2379    pub fn gpu_usage(&self) -> Option<f32> {
2380        self.inner.gpu_usage()
2381    }
2382
2383    /// Returns the GPU memory usage of all GPUs by this process in bytes. It doesn't necessarily
2384    /// mean the VRAM, just the memory used by the GPU(s).
2385    ///
2386    /// Returns `None` if it failed retrieving the information or if the current system is not
2387    /// supported.
2388    ///
2389    /// ```no_run
2390    /// use sysinfo::System;
2391    ///
2392    /// if let Ok(s) = System::new_all() {
2393    ///     for (_, process) in s.processes() {
2394    ///         println!(
2395    ///             "[Process {:?}] GPU memory usage: {:?} bytes",
2396    ///             process.pid(),
2397    ///             process.gpu_memory(),
2398    ///         );
2399    ///     }
2400    /// }
2401    /// ```
2402    #[cfg(feature = "gpu")]
2403    pub fn gpu_memory(&self) -> Option<u64> {
2404        self.inner.gpu_memory()
2405    }
2406}
2407
2408macro_rules! pid_decl {
2409    ($typ:ty) => {
2410        #[doc = include_str!("../../md_doc/pid.md")]
2411        #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
2412        #[repr(transparent)]
2413        pub struct Pid(pub(crate) $typ);
2414
2415        impl From<usize> for Pid {
2416            fn from(v: usize) -> Self {
2417                Self(v as _)
2418            }
2419        }
2420        impl From<Pid> for usize {
2421            fn from(v: Pid) -> Self {
2422                v.0 as _
2423            }
2424        }
2425        impl FromStr for Pid {
2426            type Err = <$typ as FromStr>::Err;
2427            fn from_str(s: &str) -> Result<Self, Self::Err> {
2428                Ok(Self(<$typ>::from_str(s)?))
2429            }
2430        }
2431        impl fmt::Display for Pid {
2432            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2433                write!(f, "{}", self.0)
2434            }
2435        }
2436        impl Pid {
2437            /// Allows to convert [`Pid`][crate::Pid] into [`u32`].
2438            ///
2439            /// ```
2440            /// use sysinfo::Pid;
2441            ///
2442            /// let pid = Pid::from_u32(0);
2443            /// let value: u32 = pid.as_u32();
2444            /// ```
2445            pub fn as_u32(self) -> u32 {
2446                self.0 as _
2447            }
2448            /// Allows to convert a [`u32`] into [`Pid`][crate::Pid].
2449            ///
2450            /// ```
2451            /// use sysinfo::Pid;
2452            ///
2453            /// let pid = Pid::from_u32(0);
2454            /// ```
2455            pub fn from_u32(v: u32) -> Self {
2456                Self(v as _)
2457            }
2458        }
2459    };
2460}
2461
2462cfg_select! {
2463    all(
2464        not(feature = "unknown-ci"),
2465        any(
2466            target_os = "freebsd",
2467            target_os = "netbsd",
2468            target_os = "linux",
2469            target_os = "android",
2470            target_os = "macos",
2471            target_os = "ios",
2472        )
2473    ) => {
2474        use libc::pid_t;
2475
2476        pid_decl!(pid_t);
2477    }
2478    _ => {
2479        pid_decl!(usize);
2480    }
2481}
2482
2483/// This enum allows you to specify when you want the related information to be updated.
2484///
2485/// For example if you only want the [`Process::exe()`] information to be refreshed only if it's not
2486/// already set:
2487///
2488/// ```no_run
2489/// use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System, UpdateKind};
2490///
2491/// if let Ok(mut system) = System::new() {
2492///     system.refresh_processes_specifics(
2493///         ProcessesToUpdate::All,
2494///         true,
2495///         ProcessRefreshKind::nothing().with_exe(UpdateKind::OnlyIfNotSet),
2496///     );
2497///     // Do something with processes...
2498/// }
2499/// ```
2500#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2501pub enum UpdateKind {
2502    /// Never update the related information.
2503    #[default]
2504    Never,
2505    /// Always update the related information.
2506    Always,
2507    /// Only update the related information if it was not already set at least once.
2508    OnlyIfNotSet,
2509}
2510
2511impl UpdateKind {
2512    /// If `self` is `OnlyIfNotSet`, `f` is called and its returned value is returned.
2513    #[allow(dead_code)] // Needed for unsupported targets.
2514    pub(crate) fn needs_update(self, f: impl Fn() -> bool) -> bool {
2515        match self {
2516            Self::Never => false,
2517            Self::Always => true,
2518            Self::OnlyIfNotSet => f(),
2519        }
2520    }
2521}
2522
2523/// This enum allows you to specify if you want all processes to be updated or just
2524/// some of them.
2525///
2526/// Example:
2527///
2528/// ```no_run
2529/// use sysinfo::{ProcessesToUpdate, System, get_current_pid};
2530///
2531/// if let Ok(mut system) = System::new() {
2532///     // To refresh all processes:
2533///     system.refresh_processes(ProcessesToUpdate::All, true);
2534///
2535///     // To refresh only the current one:
2536///     system.refresh_processes(
2537///         ProcessesToUpdate::Some(&[get_current_pid().unwrap()]),
2538///         true,
2539///     );
2540/// }
2541/// ```
2542#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2543pub enum ProcessesToUpdate<'a> {
2544    /// To refresh all processes.
2545    All,
2546    /// To refresh only the processes with the listed [`Pid`].
2547    ///
2548    /// [`Pid`]: crate::Pid
2549    Some(&'a [Pid]),
2550}
2551
2552/// Used to determine what you want to refresh specifically on the [`Process`] type.
2553///
2554/// When all refresh are ruled out, a [`Process`] will still retrieve the following information:
2555///  * Process ID ([`Pid`])
2556///  * Parent process ID (on Windows it never changes though)
2557///  * Process name
2558///  * Start time
2559///
2560/// ⚠️ For the `gpu_usage` and `gpu_memory` refreshes, they won't do anything unless the `gpu`
2561/// feature is enabled.
2562///
2563/// ⚠️ Just like all other refresh types, ruling out a refresh doesn't assure you that
2564/// the information won't be retrieved if the information is accessible without needing
2565/// extra computation.
2566///
2567/// ⚠️ ** Linux Specific ** ⚠️
2568/// When using `ProcessRefreshKind::everything()`, in linux we will fetch all relevant
2569/// information from `/proc/<pid>/` as well as all the information from `/proc/<pid>/task/<tid>/`
2570/// folders. This makes the refresh mechanism a lot slower depending on the number of tasks
2571/// each process has.
2572///
2573/// If you don't care about tasks information, use `ProcessRefreshKind::everything().without_tasks()`
2574/// as much as possible.
2575///
2576/// ```
2577/// use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System};
2578///
2579/// if let Ok(mut system) = System::new() {
2580///     // We don't want to update the CPU information.
2581///     system.refresh_processes_specifics(
2582///         ProcessesToUpdate::All,
2583///         true,
2584///         ProcessRefreshKind::everything().without_cpu(),
2585///     );
2586///
2587///     for (_, proc_) in system.processes() {
2588///         // We use a `==` comparison on float only because we know it's set to 0 here.
2589///         assert_eq!(proc_.cpu_usage(), 0.);
2590///     }
2591/// }
2592/// ```
2593///
2594/// [`Process`]: crate::Process
2595#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2596pub struct ProcessRefreshKind {
2597    cpu: bool,
2598    disk_usage: bool,
2599    memory: bool,
2600    user: UpdateKind,
2601    cwd: UpdateKind,
2602    root: UpdateKind,
2603    environ: UpdateKind,
2604    cmd: UpdateKind,
2605    exe: UpdateKind,
2606    tasks: bool,
2607    gpu_usage: bool,
2608    gpu_memory: bool,
2609}
2610
2611/// Creates a new `ProcessRefreshKind` with every refresh set to `false`, except for `tasks`.
2612/// By default, we want to list all processes and tasks are considered processes on their own
2613/// in linux so we still fetch them by default. However, the processes information are not
2614/// refreshed.
2615impl Default for ProcessRefreshKind {
2616    fn default() -> Self {
2617        Self {
2618            cpu: false,
2619            disk_usage: false,
2620            memory: false,
2621            user: UpdateKind::default(),
2622            cwd: UpdateKind::default(),
2623            root: UpdateKind::default(),
2624            environ: UpdateKind::default(),
2625            cmd: UpdateKind::default(),
2626            exe: UpdateKind::default(),
2627            tasks: true, // Process by default includes all tasks.
2628            gpu_usage: false,
2629            gpu_memory: false,
2630        }
2631    }
2632}
2633
2634impl ProcessRefreshKind {
2635    /// Creates a new `ProcessRefreshKind` with every refresh set to `false`, except for `tasks`.
2636    /// By default, we want to list all processes and tasks are considered processes on their own
2637    /// in linux so we still fetch them by default. However, the processes information are not
2638    /// refreshed.
2639    /// ```
2640    /// use sysinfo::{ProcessRefreshKind, UpdateKind};
2641    ///
2642    /// let r = ProcessRefreshKind::nothing();
2643    ///
2644    /// assert_eq!(r.cpu(), false);
2645    /// assert_eq!(r.user(), UpdateKind::Never);
2646    /// ```
2647    pub fn nothing() -> Self {
2648        Self::default()
2649    }
2650
2651    /// Creates a new `ProcessRefreshKind` with every refresh set to `true` or
2652    /// [`UpdateKind::OnlyIfNotSet`].
2653    ///
2654    /// ```
2655    /// use sysinfo::{ProcessRefreshKind, UpdateKind};
2656    ///
2657    /// let r = ProcessRefreshKind::everything();
2658    ///
2659    /// assert_eq!(r.cpu(), true);
2660    /// assert_eq!(r.user(), UpdateKind::OnlyIfNotSet);
2661    /// ```
2662    pub fn everything() -> Self {
2663        Self {
2664            cpu: true,
2665            disk_usage: true,
2666            memory: true,
2667            user: UpdateKind::OnlyIfNotSet,
2668            cwd: UpdateKind::OnlyIfNotSet,
2669            root: UpdateKind::OnlyIfNotSet,
2670            environ: UpdateKind::OnlyIfNotSet,
2671            cmd: UpdateKind::OnlyIfNotSet,
2672            exe: UpdateKind::OnlyIfNotSet,
2673            tasks: true,
2674            gpu_usage: true,
2675            gpu_memory: true,
2676        }
2677    }
2678
2679    impl_get_set!(
2680        ProcessRefreshKind,
2681        cpu,
2682        with_cpu,
2683        without_cpu,
2684        "\
2685It will retrieve both CPU usage and CPU accumulated time,"
2686    );
2687    impl_get_set!(
2688        ProcessRefreshKind,
2689        disk_usage,
2690        with_disk_usage,
2691        without_disk_usage
2692    );
2693    impl_get_set!(
2694        ProcessRefreshKind,
2695        user,
2696        with_user,
2697        without_user,
2698        UpdateKind,
2699        "\
2700It will retrieve the following information:
2701
2702 * user ID
2703 * user effective ID (if available on the platform)
2704 * user group ID (if available on the platform)
2705 * user effective ID (if available on the platform)"
2706    );
2707    impl_get_set!(ProcessRefreshKind, memory, with_memory, without_memory);
2708    impl_get_set!(ProcessRefreshKind, cwd, with_cwd, without_cwd, UpdateKind);
2709    impl_get_set!(
2710        ProcessRefreshKind,
2711        root,
2712        with_root,
2713        without_root,
2714        UpdateKind
2715    );
2716    impl_get_set!(
2717        ProcessRefreshKind,
2718        environ,
2719        with_environ,
2720        without_environ,
2721        UpdateKind
2722    );
2723    impl_get_set!(ProcessRefreshKind, cmd, with_cmd, without_cmd, UpdateKind);
2724    impl_get_set!(ProcessRefreshKind, exe, with_exe, without_exe, UpdateKind);
2725    impl_get_set!(ProcessRefreshKind, tasks, with_tasks, without_tasks);
2726    impl_get_set!(
2727        ProcessRefreshKind,
2728        gpu_usage,
2729        with_gpu_usage,
2730        without_gpu_usage
2731    );
2732    impl_get_set!(
2733        ProcessRefreshKind,
2734        gpu_memory,
2735        with_gpu_memory,
2736        without_gpu_memory
2737    );
2738}
2739
2740/// Used to determine what you want to refresh specifically on the [`Cpu`] type.
2741///
2742/// ⚠️ Just like all other refresh types, ruling out a refresh doesn't assure you that
2743/// the information won't be retrieved if the information is accessible without needing
2744/// extra computation.
2745///
2746/// ```
2747/// use sysinfo::{CpuRefreshKind, System};
2748///
2749/// if let Ok(mut system) = System::new() {
2750///     // We don't want to update all the CPU information.
2751///     system.refresh_cpu_specifics(CpuRefreshKind::everything().without_frequency());
2752///
2753///     for cpu in system.cpus() {
2754///         assert_eq!(cpu.frequency(), 0);
2755///     }
2756/// }
2757/// ```
2758///
2759/// [`Cpu`]: crate::Cpu
2760#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2761pub struct CpuRefreshKind {
2762    usage: bool,
2763    frequency: bool,
2764}
2765
2766impl CpuRefreshKind {
2767    /// Creates a new `CpuRefreshKind` with every refresh set to `false`.
2768    ///
2769    /// ```
2770    /// use sysinfo::CpuRefreshKind;
2771    ///
2772    /// let r = CpuRefreshKind::nothing();
2773    ///
2774    /// assert_eq!(r.frequency(), false);
2775    /// assert_eq!(r.usage(), false);
2776    /// ```
2777    pub fn nothing() -> Self {
2778        Self::default()
2779    }
2780
2781    /// Creates a new `CpuRefreshKind` with every refresh set to `true`.
2782    ///
2783    /// ```
2784    /// use sysinfo::CpuRefreshKind;
2785    ///
2786    /// let r = CpuRefreshKind::everything();
2787    ///
2788    /// assert_eq!(r.frequency(), true);
2789    /// assert_eq!(r.usage(), true);
2790    /// ```
2791    pub fn everything() -> Self {
2792        Self {
2793            usage: true,
2794            frequency: true,
2795        }
2796    }
2797
2798    impl_get_set!(CpuRefreshKind, usage, with_usage, without_usage);
2799    impl_get_set!(CpuRefreshKind, frequency, with_frequency, without_frequency);
2800}
2801
2802/// Used to determine which memory you want to refresh specifically.
2803///
2804/// ⚠️ Just like all other refresh types, ruling out a refresh doesn't assure you that
2805/// the information won't be retrieved if the information is accessible without needing
2806/// extra computation.
2807///
2808/// ```
2809/// use sysinfo::{MemoryRefreshKind, System};
2810///
2811/// if let Ok(mut system) = System::new() {
2812///     // We don't want to update all memories information.
2813///     system.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
2814///
2815///     println!("total RAM: {}", system.total_memory());
2816///     println!("free RAM:  {}", system.free_memory());
2817/// }
2818/// ```
2819#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2820pub struct MemoryRefreshKind {
2821    ram: bool,
2822    swap: bool,
2823}
2824
2825impl MemoryRefreshKind {
2826    /// Creates a new `MemoryRefreshKind` with every refresh set to `false`.
2827    ///
2828    /// ```
2829    /// use sysinfo::MemoryRefreshKind;
2830    ///
2831    /// let r = MemoryRefreshKind::nothing();
2832    ///
2833    /// assert_eq!(r.ram(), false);
2834    /// assert_eq!(r.swap(), false);
2835    /// ```
2836    pub fn nothing() -> Self {
2837        Self::default()
2838    }
2839
2840    /// Creates a new `MemoryRefreshKind` with every refresh set to `true`.
2841    ///
2842    /// ```
2843    /// use sysinfo::MemoryRefreshKind;
2844    ///
2845    /// let r = MemoryRefreshKind::everything();
2846    ///
2847    /// assert_eq!(r.ram(), true);
2848    /// assert_eq!(r.swap(), true);
2849    /// ```
2850    pub fn everything() -> Self {
2851        Self {
2852            ram: true,
2853            swap: true,
2854        }
2855    }
2856
2857    impl_get_set!(MemoryRefreshKind, ram, with_ram, without_ram);
2858    impl_get_set!(MemoryRefreshKind, swap, with_swap, without_swap);
2859}
2860
2861/// Used to determine what you want to refresh specifically on the [`System`][crate::System] type.
2862///
2863/// ⚠️ Just like all other refresh types, ruling out a refresh doesn't assure you that
2864/// the information won't be retrieved if the information is accessible without needing
2865/// extra computation.
2866///
2867/// ```
2868/// use sysinfo::{RefreshKind, System};
2869///
2870/// // We want everything except memory.
2871/// if let Ok(mut system) = System::new_with_specifics(RefreshKind::everything().without_memory()) {
2872///     assert_eq!(system.total_memory(), 0);
2873///     # if !cfg!(feature = "apple-sandbox") {
2874///     assert!(system.processes().len() > 0);
2875///     # }
2876/// }
2877/// ```
2878#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2879pub struct RefreshKind {
2880    processes: Option<ProcessRefreshKind>,
2881    memory: Option<MemoryRefreshKind>,
2882    cpu: Option<CpuRefreshKind>,
2883}
2884
2885impl RefreshKind {
2886    /// Creates a new `RefreshKind` with every refresh set to `false`/`None`.
2887    ///
2888    /// ```
2889    /// use sysinfo::RefreshKind;
2890    ///
2891    /// let r = RefreshKind::nothing();
2892    ///
2893    /// assert_eq!(r.processes().is_some(), false);
2894    /// assert_eq!(r.memory().is_some(), false);
2895    /// assert_eq!(r.cpu().is_some(), false);
2896    /// ```
2897    pub fn nothing() -> Self {
2898        Self::default()
2899    }
2900
2901    /// Creates a new `RefreshKind` with every refresh set to `true`/`Some(...)`.
2902    ///
2903    /// ```
2904    /// use sysinfo::RefreshKind;
2905    ///
2906    /// let r = RefreshKind::everything();
2907    ///
2908    /// assert_eq!(r.processes().is_some(), true);
2909    /// assert_eq!(r.memory().is_some(), true);
2910    /// assert_eq!(r.cpu().is_some(), true);
2911    /// ```
2912    pub fn everything() -> Self {
2913        Self {
2914            processes: Some(ProcessRefreshKind::everything()),
2915            memory: Some(MemoryRefreshKind::everything()),
2916            cpu: Some(CpuRefreshKind::everything()),
2917        }
2918    }
2919
2920    impl_get_set!(
2921        RefreshKind,
2922        processes,
2923        with_processes,
2924        without_processes,
2925        ProcessRefreshKind
2926    );
2927    impl_get_set!(
2928        RefreshKind,
2929        memory,
2930        with_memory,
2931        without_memory,
2932        MemoryRefreshKind
2933    );
2934    impl_get_set!(RefreshKind, cpu, with_cpu, without_cpu, CpuRefreshKind);
2935}
2936
2937/// Returns the pid for the current process.
2938///
2939/// `Err` is returned in case the platform isn't supported.
2940///
2941/// ```no_run
2942/// use sysinfo::get_current_pid;
2943///
2944/// match get_current_pid() {
2945///     Ok(pid) => {
2946///         println!("current pid: {}", pid);
2947///     }
2948///     Err(e) => {
2949///         println!("failed to get current pid: {}", e);
2950///     }
2951/// }
2952/// ```
2953#[allow(clippy::unnecessary_wraps)]
2954pub fn get_current_pid() -> Result<Pid, Error> {
2955    cfg_select! {
2956        feature = "unknown-ci" => {
2957            fn inner() -> Result<Pid, Error> {
2958                Err(Error::Unsupported)
2959            }
2960        }
2961        any(
2962            target_os = "freebsd",
2963            target_os = "netbsd",
2964            target_os = "linux",
2965            target_os = "android",
2966            target_os = "macos",
2967            target_os = "ios",
2968        ) => {
2969            fn inner() -> Result<Pid, Error> {
2970                unsafe { Ok(Pid(libc::getpid())) }
2971            }
2972        }
2973        windows => {
2974            fn inner() -> Result<Pid, Error> {
2975                use windows::Win32::System::Threading::GetCurrentProcessId;
2976
2977                unsafe { Ok(Pid(GetCurrentProcessId() as _)) }
2978            }
2979        }
2980        _ => {
2981            fn inner() -> Result<Pid, Error> {
2982                Err(Error::Unsupported)
2983            }
2984        }
2985    }
2986    inner()
2987}
2988
2989/// Contains all the methods of the [`Cpu`][crate::Cpu] struct.
2990///
2991/// ```no_run
2992/// use sysinfo::{System, RefreshKind, CpuRefreshKind};
2993///
2994/// if let Ok(mut s) = System::new_with_specifics(
2995///     RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
2996/// ) {
2997///     // Wait a bit because CPU usage is based on diff.
2998///     std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
2999///     // Refresh CPUs again to get actual value.
3000///     s.refresh_cpu_all();
3001///
3002///     for cpu in s.cpus() {
3003///         println!("{}%", cpu.usage());
3004///     }
3005/// }
3006/// ```
3007pub struct Cpu {
3008    pub(crate) inner: CpuInner,
3009}
3010
3011impl Cpu {
3012    /// Returns this CPU's usage.
3013    ///
3014    /// Note: You'll need to refresh it at least twice (diff between the first and the second is
3015    /// how CPU usage is computed) at first if you want to have a non-zero value.
3016    ///
3017    /// ```no_run
3018    /// use sysinfo::{System, RefreshKind, CpuRefreshKind};
3019    ///
3020    /// if let Ok(mut s) = System::new_with_specifics(
3021    ///     RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
3022    /// ) {
3023    ///     // Wait a bit because CPU usage is based on diff.
3024    ///     std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
3025    ///     // Refresh CPUs again to get actual value.
3026    ///     s.refresh_cpu_all();
3027    ///
3028    ///     for cpu in s.cpus() {
3029    ///         println!("{}%", cpu.usage());
3030    ///     }
3031    /// }
3032    /// ```
3033    pub fn usage(&self) -> f32 {
3034        self.inner.cpu_usage()
3035    }
3036
3037    /// Returns this CPU's name.
3038    ///
3039    /// ```no_run
3040    /// use sysinfo::{System, RefreshKind, CpuRefreshKind};
3041    ///
3042    /// if let Ok(s) = System::new_with_specifics(
3043    ///     RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
3044    /// ) {
3045    ///     for cpu in s.cpus() {
3046    ///         println!("{}", cpu.name());
3047    ///     }
3048    /// }
3049    /// ```
3050    pub fn name(&self) -> &str {
3051        self.inner.name()
3052    }
3053
3054    /// Returns the CPU's vendor id.
3055    ///
3056    /// ```no_run
3057    /// use sysinfo::{System, RefreshKind, CpuRefreshKind};
3058    ///
3059    /// if let Ok(s) = System::new_with_specifics(
3060    ///     RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
3061    /// ) {
3062    ///     for cpu in s.cpus() {
3063    ///         println!("{}", cpu.vendor_id());
3064    ///     }
3065    /// }
3066    /// ```
3067    pub fn vendor_id(&self) -> &str {
3068        self.inner.vendor_id()
3069    }
3070
3071    /// Returns the CPU's brand.
3072    ///
3073    /// ```no_run
3074    /// use sysinfo::{System, RefreshKind, CpuRefreshKind};
3075    ///
3076    /// if let Ok(s) = System::new_with_specifics(
3077    ///     RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
3078    /// ) {
3079    ///     for cpu in s.cpus() {
3080    ///         println!("{}", cpu.brand());
3081    ///     }
3082    /// }
3083    /// ```
3084    pub fn brand(&self) -> &str {
3085        self.inner.brand()
3086    }
3087
3088    /// Returns the CPU's frequency (in MHz).
3089    ///
3090    /// ```no_run
3091    /// use sysinfo::{System, RefreshKind, CpuRefreshKind};
3092    ///
3093    /// if let Ok(s) = System::new_with_specifics(
3094    ///     RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
3095    /// ) {
3096    ///     for cpu in s.cpus() {
3097    ///         println!("{}", cpu.frequency());
3098    ///     }
3099    /// }
3100    /// ```
3101    pub fn frequency(&self) -> u64 {
3102        self.inner.frequency()
3103    }
3104}
3105
3106#[cfg(test)]
3107mod test {
3108    use crate::*;
3109    use std::str::FromStr;
3110
3111    // In case `Process::updated` is misused, `System::refresh_processes` might remove them
3112    // so this test ensures that it doesn't happen.
3113    #[test]
3114    fn check_refresh_process_update() {
3115        if let Ok(mut s) = System::new_all() {
3116            let total = s.processes().len() as isize;
3117            s.refresh_processes(ProcessesToUpdate::All, false);
3118            let new_total = s.processes().len() as isize;
3119            // There should be almost no difference in the processes count.
3120            assert!(
3121                (new_total - total).abs() <= 5,
3122                "{} <= 5",
3123                (new_total - total).abs()
3124            );
3125        }
3126    }
3127
3128    #[test]
3129    fn check_cpu_arch() {
3130        assert!(!System::cpu_arch().is_empty());
3131    }
3132
3133    // Ensure that the CPUs frequency isn't retrieved until we ask for it.
3134    #[test]
3135    fn check_cpu_frequency() {
3136        let Ok(mut s) = System::new() else { return };
3137        s.refresh_processes(ProcessesToUpdate::All, false);
3138        for proc_ in s.cpus() {
3139            assert_eq!(proc_.frequency(), 0);
3140        }
3141        s.refresh_cpu_usage();
3142        for proc_ in s.cpus() {
3143            assert_eq!(proc_.frequency(), 0);
3144        }
3145        // In a VM, it'll fail.
3146        if std::env::var("APPLE_CI").is_ok()
3147            || std::env::var("FREEBSD_CI").is_ok()
3148            || std::env::var("NETBSD_CI").is_ok()
3149        {
3150            return;
3151        }
3152        s.refresh_cpu_specifics(CpuRefreshKind::everything());
3153        for proc_ in s.cpus() {
3154            assert_ne!(proc_.frequency(), 0);
3155        }
3156    }
3157
3158    #[test]
3159    fn check_process_memory_usage() {
3160        let Ok(mut s) = System::new() else { return };
3161        s.refresh_specifics(RefreshKind::everything());
3162
3163        if !cfg!(feature = "apple-sandbox") {
3164            // No process should have 0 as memory usage.
3165            assert!(!s.processes().iter().all(|(_, proc_)| proc_.memory() == 0));
3166        } else {
3167            // There should be no process, but if there is one, its memory usage should be 0.
3168            assert!(s.processes().iter().all(|(_, proc_)| proc_.memory() == 0));
3169        }
3170    }
3171
3172    #[test]
3173    fn check_system_implemented_traits() {
3174        fn check<T: Sized + std::fmt::Debug + Send + Sync>(_: T) {}
3175
3176        if let Ok(s) = System::new() {
3177            check(s);
3178        }
3179    }
3180
3181    #[test]
3182    fn check_memory_usage() {
3183        let Ok(mut s) = System::new() else { return };
3184
3185        assert_eq!(s.total_memory(), 0);
3186        assert_eq!(s.free_memory(), 0);
3187        assert_eq!(s.available_memory(), 0);
3188        assert_eq!(s.used_memory(), 0);
3189        assert_eq!(s.total_swap(), 0);
3190        assert_eq!(s.free_swap(), 0);
3191        assert_eq!(s.used_swap(), 0);
3192
3193        s.refresh_memory();
3194        if !cfg!(feature = "apple-sandbox") {
3195            assert!(s.total_memory() > 0);
3196            assert!(s.used_memory() > 0);
3197            if s.total_swap() > 0 {
3198                // I think it's pretty safe to assume that there is still some swap left...
3199                assert!(s.free_swap() > 0);
3200            }
3201        } else {
3202            assert_eq!(s.total_memory(), 0);
3203            assert_eq!(s.used_memory(), 0);
3204            assert_eq!(s.total_swap(), 0);
3205            assert_eq!(s.free_swap(), 0);
3206        }
3207    }
3208
3209    #[cfg(target_os = "linux")]
3210    #[test]
3211    fn check_processes_cpu_usage() {
3212        let Ok(mut s) = System::new() else { return };
3213
3214        s.refresh_processes(ProcessesToUpdate::All, false);
3215        // All CPU usage will start at zero until the second refresh
3216        assert!(
3217            s.processes()
3218                .iter()
3219                .all(|(_, proc_)| proc_.cpu_usage() == 0.0)
3220        );
3221
3222        // Wait a bit to update CPU usage values
3223        std::thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL);
3224        s.refresh_processes(ProcessesToUpdate::All, true);
3225        assert!(
3226            s.processes()
3227                .iter()
3228                .all(|(_, proc_)| proc_.cpu_usage() >= 0.0
3229                    && proc_.cpu_usage() <= (s.cpus().len() as f32) * 100.0)
3230        );
3231        assert!(
3232            s.processes()
3233                .iter()
3234                .any(|(_, proc_)| proc_.cpu_usage() > 0.0)
3235        );
3236    }
3237
3238    #[test]
3239    fn check_cpu_usage() {
3240        let Ok(mut s) = System::new() else { return };
3241        for _ in 0..10 {
3242            s.refresh_cpu_usage();
3243            // Wait a bit to update CPU usage values
3244            std::thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL);
3245            if s.cpus().iter().any(|c| c.usage() > 0.0) {
3246                // All good!
3247                return;
3248            }
3249        }
3250        panic!("CPU usage is always zero...");
3251    }
3252
3253    #[test]
3254    fn check_system_info() {
3255        // We don't want to test on unsupported systems.
3256        if System::new().is_ok() {
3257            assert!(
3258                !System::name()
3259                    .expect("Failed to get system name")
3260                    .is_empty()
3261            );
3262
3263            assert!(
3264                !System::kernel_version()
3265                    .expect("Failed to get kernel version")
3266                    .is_empty()
3267            );
3268
3269            assert!(
3270                !System::os_version()
3271                    .expect("Failed to get os version")
3272                    .is_empty()
3273            );
3274
3275            assert!(
3276                !System::long_os_version()
3277                    .expect("Failed to get long OS version")
3278                    .is_empty()
3279            );
3280        }
3281
3282        assert!(!System::distribution_id().is_empty());
3283    }
3284
3285    #[test]
3286    fn check_host_name() {
3287        // We don't want to test on unsupported systems.
3288        if System::new().is_ok() {
3289            assert!(System::host_name().is_ok());
3290        }
3291    }
3292
3293    #[test]
3294    fn check_refresh_process_return_value() {
3295        // We don't want to test on unsupported systems.
3296        if System::new().is_ok() {
3297            let _pid = get_current_pid().expect("Failed to get current PID");
3298
3299            #[cfg(not(feature = "apple-sandbox"))]
3300            {
3301                let Ok(mut s) = System::new() else { return };
3302                // First check what happens in case the process isn't already in our process list.
3303                assert_eq!(
3304                    s.refresh_processes(ProcessesToUpdate::Some(&[_pid]), true),
3305                    1
3306                );
3307                // Then check that it still returns 1 if the process is already in our process list.
3308                assert_eq!(
3309                    s.refresh_processes(ProcessesToUpdate::Some(&[_pid]), true),
3310                    1
3311                );
3312            }
3313        }
3314    }
3315
3316    #[test]
3317    fn check_cpus_number() {
3318        let Ok(mut s) = System::new() else { return };
3319
3320        // This information isn't retrieved by default.
3321        assert!(s.cpus().is_empty());
3322        if System::new().is_ok() {
3323            // The physical cores count is recomputed every time the function is called, so the
3324            // information must be relevant even with nothing initialized.
3325            let physical_cores_count =
3326                System::physical_core_count().expect("failed to get number of physical cores");
3327
3328            s.refresh_cpu_usage();
3329            // The cpus shouldn't be empty anymore.
3330            assert!(!s.cpus().is_empty());
3331
3332            // In case we are running inside a VM, it's possible to not have a physical core, only
3333            // logical ones, which is why we don't test `physical_cores_count > 0`.
3334            let physical_cores_count2 =
3335                System::physical_core_count().expect("failed to get number of physical cores");
3336            assert!(physical_cores_count2 <= s.cpus().len());
3337            assert_eq!(physical_cores_count, physical_cores_count2);
3338        } else {
3339            assert!(matches!(
3340                System::physical_core_count(),
3341                Err(crate::Error::Unsupported)
3342            ));
3343        }
3344        assert!(System::physical_core_count().unwrap_or(0) <= s.cpus().len());
3345    }
3346
3347    // This test only exists to ensure that the `Display` and `Debug` traits are implemented on the
3348    // `ProcessStatus` enum on all targets.
3349    #[test]
3350    fn check_display_impl_process_status() {
3351        println!("{} {:?}", ProcessStatus::Parked, ProcessStatus::Idle);
3352    }
3353
3354    #[test]
3355    #[allow(clippy::unnecessary_fallible_conversions)]
3356    fn check_pid_from_impls() {
3357        assert!(crate::Pid::try_from(0usize).is_ok());
3358        // If it doesn't panic, it's fine.
3359        let _ = crate::Pid::from(0);
3360        assert!(crate::Pid::from_str("0").is_ok());
3361    }
3362
3363    #[test]
3364    #[allow(clippy::const_is_empty)]
3365    fn check_nb_supported_signals() {
3366        if System::new().is_ok() {
3367            assert!(
3368                !SUPPORTED_SIGNALS.is_empty(),
3369                "SUPPORTED_SIGNALS shouldn't be empty on supported systems!"
3370            );
3371        } else {
3372            assert!(
3373                SUPPORTED_SIGNALS.is_empty(),
3374                "SUPPORTED_SIGNALS should be empty on not support systems!"
3375            );
3376        }
3377    }
3378}
3379
3380#[cfg(doctest)]
3381mod doctest {
3382    // FIXME: Can be removed once negative trait bounds are supported.
3383    /// Check that `Process` doesn't implement `Clone`.
3384    ///
3385    /// First we check that the "basic" code works:
3386    ///
3387    /// ```no_run
3388    /// use sysinfo::{Process, System};
3389    ///
3390    /// if let Ok(mut s) = System::new_all() {
3391    ///     let p: &Process = s.processes().values().next().unwrap();
3392    /// }
3393    /// ```
3394    ///
3395    /// And now we check if it fails when we try to clone it:
3396    ///
3397    /// ```compile_fail
3398    /// use sysinfo::{Process, System};
3399    ///
3400    /// if let Ok(mut s) = System::new_all() {
3401    ///     let p: &Process = s.processes().values().next().unwrap();
3402    ///     let p = (*p).clone();
3403    /// }
3404    /// ```
3405    mod process_clone {}
3406
3407    // FIXME: Can be removed once negative trait bounds are supported.
3408    /// Check that `System` doesn't implement `Clone`.
3409    ///
3410    /// First we check that the "basic" code works:
3411    ///
3412    /// ```no_run
3413    /// use sysinfo::{Process, System};
3414    ///
3415    /// if let Ok(s) = System::new() {}
3416    /// ```
3417    ///
3418    /// And now we check if it fails when we try to clone it:
3419    ///
3420    /// ```compile_fail
3421    /// use sysinfo::{Process, System};
3422    ///
3423    /// if let Ok(s) = System::new() {
3424    ///     let s = s.clone();
3425    /// }
3426    /// ```
3427    mod system_clone {}
3428}