sysinfo

Struct System

Source
pub struct System { /* private fields */ }
Expand description

Structs containing system’s information such as processes, memory and CPU.

use sysinfo::System;

if sysinfo::IS_SUPPORTED_SYSTEM {
    println!("System: {:?}", System::new_all());
} else {
    println!("This OS isn't supported (yet?).");
}

Implementations§

Source§

impl System

Source

pub fn new() -> Self

Creates a new System instance with nothing loaded.

Use one of the refresh methods (like refresh_all) to update its internal information.

use sysinfo::System;

let s = System::new();
Source

pub fn new_all() -> Self

Creates a new System instance with everything loaded.

It is an equivalent of System::new_with_specifics(RefreshKind::everything()).

use sysinfo::System;

let s = System::new_all();
Examples found in repository?
examples/simple.rs (line 462)
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
fn main() {
    println!("Getting system information...");
    let mut system = System::new_all();
    let mut networks = Networks::new_with_refreshed_list();
    let mut disks = Disks::new_with_refreshed_list();
    let mut components = Components::new_with_refreshed_list();
    let mut users = Users::new_with_refreshed_list();

    println!("Done.");
    let t_stin = io::stdin();
    let mut stin = t_stin.lock();
    let mut done = false;

    println!("To get the commands' list, enter 'help'.");
    while !done {
        let mut input = String::new();
        write!(&mut io::stdout(), "> ");
        io::stdout().flush();

        stin.read_line(&mut input);
        if input.is_empty() {
            // The string is empty, meaning there is no '\n', meaning
            // that the user used CTRL+D so we can just quit!
            println!("\nLeaving, bye!");
            break;
        }
        if (&input as &str).ends_with('\n') {
            input.pop();
        }
        done = interpret_input(
            input.as_ref(),
            &mut system,
            &mut networks,
            &mut disks,
            &mut components,
            &mut users,
        );
    }
}
Source

pub fn new_with_specifics(refreshes: RefreshKind) -> Self

Creates a new System instance and refresh the data corresponding to the given RefreshKind.

use sysinfo::{ProcessRefreshKind, RefreshKind, System};

// We want to only refresh processes.
let mut system = System::new_with_specifics(
     RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
);

assert!(!system.processes().is_empty());
Source

pub fn refresh_specifics(&mut self, refreshes: RefreshKind)

Refreshes according to the given RefreshKind. It calls the corresponding “refresh_” methods.

use sysinfo::{ProcessRefreshKind, RefreshKind, System};

let mut s = System::new_all();

// Let's just update processes:
s.refresh_specifics(
    RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
);
Source

pub fn refresh_all(&mut self)

Refreshes all system and processes information.

It is the same as calling system.refresh_specifics(RefreshKind::everything()).

Don’t forget to take a look at ProcessRefreshKind::everything method to see what it will update for processes more in details.

use sysinfo::System;

let mut s = System::new();
s.refresh_all();
Examples found in repository?
examples/simple.rs (line 401)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn refresh_memory(&mut self)

Refreshes RAM and SWAP usage.

It is the same as calling system.refresh_memory_specifics(MemoryRefreshKind::everything()).

If you don’t want to refresh both, take a look at System::refresh_memory_specifics.

use sysinfo::System;

let mut s = System::new();
s.refresh_memory();
Source

pub fn refresh_memory_specifics(&mut self, refresh_kind: MemoryRefreshKind)

Refreshes system memory specific information.

use sysinfo::{MemoryRefreshKind, System};

let mut s = System::new();
s.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
Source

pub fn refresh_cpu_usage(&mut self)

Refreshes CPUs usage.

⚠️ Please note that the result will very likely be inaccurate at the first call. You need to call this method at least twice (with a bit of time between each call, like 200 ms, take a look at MINIMUM_CPU_UPDATE_INTERVAL for more information) to get accurate value as it uses previous results to compute the next value.

Calling this method is the same as calling system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_cpu_usage()).

use sysinfo::System;

let mut s = System::new_all();
// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPUs again.
s.refresh_cpu_usage();
Source

pub fn refresh_cpu_frequency(&mut self)

Refreshes CPUs frequency information.

Calling this method is the same as calling system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_frequency()).

use sysinfo::System;

let mut s = System::new_all();
s.refresh_cpu_frequency();
Source

pub fn refresh_cpu_list(&mut self, refresh_kind: CpuRefreshKind)

Refreshes the list of CPU.

Normally, this should almost never be needed as it’s pretty rare for a computer to add a CPU while running, but it’s possible on some computers which shutdown CPU if the load is low enough.

The refresh_kind argument tells what information you want to be retrieved for each CPU.

use sysinfo::{CpuRefreshKind, System};

let mut s = System::new_all();
// We already have the list of CPU filled, but we want to recompute it
// in case new CPUs were added.
s.refresh_cpu_list(CpuRefreshKind::everything());
Source

pub fn refresh_cpu_all(&mut self)

Refreshes all information related to CPUs information.

If you only want the CPU usage, use System::refresh_cpu_usage instead.

⚠️ Please note that the result will be inaccurate at the first call. You need to call this method at least twice (with a bit of time between each call, like 200 ms, take a look at MINIMUM_CPU_UPDATE_INTERVAL for more information) to get accurate value as it uses previous results to compute the next value.

Calling this method is the same as calling system.refresh_cpu_specifics(CpuRefreshKind::everything()).

use sysinfo::System;

let mut s = System::new_all();
s.refresh_cpu_all();
Examples found in repository?
examples/simple.rs (line 181)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn refresh_cpu_specifics(&mut self, refresh_kind: CpuRefreshKind)

Refreshes CPUs specific information.

use sysinfo::{System, CpuRefreshKind};

let mut s = System::new_all();
s.refresh_cpu_specifics(CpuRefreshKind::everything());
Source

pub fn refresh_processes( &mut self, processes_to_update: ProcessesToUpdate<'_>, remove_dead_processes: bool, ) -> usize

Gets all processes and updates their information.

It does the same as:

system.refresh_processes_specifics(
    ProcessesToUpdate::All,
    true,
    ProcessRefreshKind::nothing()
        .with_memory()
        .with_cpu()
        .with_disk_usage()
        .with_exe(UpdateKind::OnlyIfNotSet),
);

⚠️ remove_dead_processes works as follows: if an updated process is dead, then it is removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed since 7 is not part of the update.

⚠️ On Linux, sysinfo keeps the stat files open by default. You can change this behaviour by using set_open_files_limit.

Example:

use sysinfo::{ProcessesToUpdate, System};

let mut s = System::new_all();
s.refresh_processes(ProcessesToUpdate::All, true);
Examples found in repository?
examples/simple.rs (line 411)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn refresh_processes_specifics( &mut self, processes_to_update: ProcessesToUpdate<'_>, remove_dead_processes: bool, refresh_kind: ProcessRefreshKind, ) -> usize

Gets all processes and updates the specified information.

Returns the number of updated processes.

⚠️ remove_dead_processes works as follows: if an updated process is dead, then it is removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed since 7 is not part of the update.

⚠️ On Linux, sysinfo keeps the stat files open by default. You can change this behaviour by using set_open_files_limit.

use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System};

let mut s = System::new_all();
s.refresh_processes_specifics(
    ProcessesToUpdate::All,
    true,
    ProcessRefreshKind::everything(),
);
Source

pub fn processes(&self) -> &HashMap<Pid, Process>

Returns the process list.

use sysinfo::System;

let s = System::new_all();
for (pid, process) in s.processes() {
    println!("{} {:?}", pid, process.name());
}
Examples found in repository?
examples/simple.rs (line 240)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn process(&self, pid: Pid) -> Option<&Process>

Returns the process corresponding to the given pid or None if no such process exists.

use sysinfo::{Pid, System};

let s = System::new_all();
if let Some(process) = s.process(Pid::from(1337)) {
    println!("{:?}", process.name());
}
Examples found in repository?
examples/simple.rs (line 286)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn processes_by_name<'a: 'b, 'b>( &'a self, name: &'b OsStr, ) -> impl Iterator<Item = &'a Process> + 'b

Returns an iterator of process containing the given name.

If you want only the processes with exactly the given name, take a look at System::processes_by_exact_name.

⚠️ Important ⚠️

On Linux, there are two things to know about processes’ name:

  1. It is limited to 15 characters.
  2. It is not always the exe name.
use sysinfo::System;

let s = System::new_all();
for process in s.processes_by_name("htop".as_ref()) {
    println!("{} {:?}", process.pid(), process.name());
}
Examples found in repository?
examples/simple.rs (line 292)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn processes_by_exact_name<'a: 'b, 'b>( &'a self, name: &'b OsStr, ) -> impl Iterator<Item = &'a Process> + 'b

Returns an iterator of processes with exactly the given name.

If you instead want the processes containing name, take a look at System::processes_by_name.

⚠️ Important ⚠️

On Linux, there are two things to know about processes’ name:

  1. It is limited to 15 characters.
  2. It is not always the exe name.
use sysinfo::System;

let s = System::new_all();
for process in s.processes_by_exact_name("htop".as_ref()) {
    println!("{} {:?}", process.pid(), process.name());
}
Source

pub fn global_cpu_usage(&self) -> f32

Returns “global” CPUs usage (aka the addition of all the CPUs).

To have up-to-date information, you need to call System::refresh_cpu_specifics or System::refresh_specifics with cpu enabled.

use sysinfo::{CpuRefreshKind, RefreshKind, System};

let mut s = System::new_with_specifics(
    RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
);
// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPUs again to get actual value.
s.refresh_cpu_usage();
println!("{}%", s.global_cpu_usage());
Examples found in repository?
examples/simple.rs (line 205)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn cpus(&self) -> &[Cpu]

Returns the list of the CPUs.

By default, the list of CPUs is empty until you call System::refresh_cpu_specifics or System::refresh_specifics with cpu enabled.

use sysinfo::{CpuRefreshKind, RefreshKind, System};

let mut s = System::new_with_specifics(
    RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
);
// Wait a bit because CPU usage is based on diff.
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
// Refresh CPUs again to get actual value.
s.refresh_cpu_usage();
for cpu in s.cpus() {
    println!("{}%", cpu.cpu_usage());
}
Examples found in repository?
examples/simple.rs (line 207)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn physical_core_count(&self) -> Option<usize>

Returns the number of physical cores on the CPU or None if it couldn’t get it.

In case there are multiple CPUs, it will combine the physical core count of all the CPUs.

Important: this information is computed every time this function is called.

use sysinfo::System;

let s = System::new();
println!("{:?}", s.physical_core_count());
Examples found in repository?
examples/simple.rs (line 198)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn total_memory(&self) -> u64

Returns the RAM size in bytes.

use sysinfo::System;

let s = System::new_all();
println!("{} bytes", s.total_memory());

On Linux, if you want to see this information with the limit of your cgroup, take a look at cgroup_limits.

Examples found in repository?
examples/simple.rs (line 215)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn free_memory(&self) -> u64

Returns the amount of free RAM in bytes.

Generally, “free” memory refers to unallocated memory whereas “available” memory refers to memory that is available for (re)use.

Side note: Windows doesn’t report “free” memory so this method returns the same value as available_memory.

use sysinfo::System;

let s = System::new_all();
println!("{} bytes", s.free_memory());
Source

pub fn available_memory(&self) -> u64

Returns the amount of available RAM in bytes.

Generally, “free” memory refers to unallocated memory whereas “available” memory refers to memory that is available for (re)use.

⚠️ Windows and FreeBSD don’t report “available” memory so System::free_memory returns the same value as this method.

use sysinfo::System;

let s = System::new_all();
println!("{} bytes", s.available_memory());
Examples found in repository?
examples/simple.rs (line 220)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn used_memory(&self) -> u64

Returns the amount of used RAM in bytes.

use sysinfo::System;

let s = System::new_all();
println!("{} bytes", s.used_memory());
Examples found in repository?
examples/simple.rs (line 225)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn total_swap(&self) -> u64

Returns the SWAP size in bytes.

use sysinfo::System;

let s = System::new_all();
println!("{} bytes", s.total_swap());
Examples found in repository?
examples/simple.rs (line 230)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn free_swap(&self) -> u64

Returns the amount of free SWAP in bytes.

use sysinfo::System;

let s = System::new_all();
println!("{} bytes", s.free_swap());
Source

pub fn used_swap(&self) -> u64

Returns the amount of used SWAP in bytes.

use sysinfo::System;

let s = System::new_all();
println!("{} bytes", s.used_swap());
Examples found in repository?
examples/simple.rs (line 235)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn cgroup_limits(&self) -> Option<CGroupLimits>

Retrieves the limits for the current cgroup (if any), otherwise it returns None.

This information is computed every time the method is called.

⚠️ You need to have run refresh_memory at least once before calling this method.

⚠️ This method is only implemented for Linux. It always returns None for all other systems.

use sysinfo::System;

let s = System::new_all();
println!("limits: {:?}", s.cgroup_limits());
Source

pub fn uptime() -> u64

Returns system uptime (in seconds).

Important: this information is computed every time this function is called.

use sysinfo::System;

println!("System running since {} seconds", System::uptime());
Examples found in repository?
examples/simple.rs (line 386)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn boot_time() -> u64

Returns the time (in seconds) when the system booted since UNIX epoch.

Important: this information is computed every time this function is called.

use sysinfo::System;

println!("System booted at {} seconds", System::boot_time());
Examples found in repository?
examples/simple.rs (line 383)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn load_average() -> LoadAvg

Returns the system load average value.

Important: this information is computed every time this function is called.

⚠️ This is currently not working on Windows.

use sysinfo::System;

let load_avg = System::load_average();
println!(
    "one minute: {}%, five minutes: {}%, fifteen minutes: {}%",
    load_avg.one,
    load_avg.five,
    load_avg.fifteen,
);
Examples found in repository?
examples/simple.rs (line 271)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn name() -> Option<String>

Returns the system name.

Important: this information is computed every time this function is called.

use sysinfo::System;

println!("OS: {:?}", System::name());
Examples found in repository?
examples/simple.rs (line 442)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn kernel_version() -> Option<String>

Returns the system’s kernel version.

Important: this information is computed every time this function is called.

use sysinfo::System;

println!("kernel version: {:?}", System::kernel_version());
Examples found in repository?
examples/simple.rs (line 443)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn os_version() -> Option<String>

Returns the system version (e.g. for MacOS this will return 11.1 rather than the kernel version).

Important: this information is computed every time this function is called.

use sysinfo::System;

println!("OS version: {:?}", System::os_version());
Examples found in repository?
examples/simple.rs (line 444)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn long_os_version() -> Option<String>

Returns the system long os version (e.g “MacOS 11.2 BigSur”).

Important: this information is computed every time this function is called.

use sysinfo::System;

println!("Long OS Version: {:?}", System::long_os_version());
Examples found in repository?
examples/simple.rs (line 445)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn distribution_id() -> String

Returns the distribution id as defined by os-release, or [std::env::consts::OS].

See also

Important: this information is computed every time this function is called.

use sysinfo::System;

println!("Distribution ID: {:?}", System::distribution_id());
Source

pub fn host_name() -> Option<String>

Returns the system hostname based off DNS.

Important: this information is computed every time this function is called.

use sysinfo::System;

println!("Hostname: {:?}", System::host_name());
Examples found in repository?
examples/simple.rs (line 446)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
fn interpret_input(
    input: &str,
    sys: &mut System,
    networks: &mut Networks,
    disks: &mut Disks,
    components: &mut Components,
    users: &mut Users,
) -> bool {
    match input.trim() {
        "help" => print_help(),
        "refresh_disks" => {
            writeln!(&mut io::stdout(), "Refreshing disk list...");
            disks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_users" => {
            writeln!(&mut io::stdout(), "Refreshing user list...");
            users.refresh();
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_networks" => {
            writeln!(&mut io::stdout(), "Refreshing network list...");
            networks.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_components" => {
            writeln!(&mut io::stdout(), "Refreshing component list...");
            components.refresh(true);
            writeln!(&mut io::stdout(), "Done.");
        }
        "refresh_cpu" => {
            writeln!(&mut io::stdout(), "Refreshing CPUs...");
            sys.refresh_cpu_all();
            writeln!(&mut io::stdout(), "Done.");
        }
        "signals" => {
            let mut nb = 1i32;

            for sig in signals {
                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
                nb += 1;
            }
        }
        "cpus" => {
            // Note: you should refresh a few times before using this, so that usage statistics
            // can be ascertained
            writeln!(
                &mut io::stdout(),
                "number of physical cores: {}",
                sys.physical_core_count()
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "Unknown".to_owned()),
            );
            writeln!(
                &mut io::stdout(),
                "total CPU usage: {}%",
                sys.global_cpu_usage(),
            );
            for cpu in sys.cpus() {
                writeln!(&mut io::stdout(), "{cpu:?}");
            }
        }
        "memory" => {
            writeln!(
                &mut io::stdout(),
                "total memory:     {: >10} KB",
                sys.total_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "available memory: {: >10} KB",
                sys.available_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used memory:      {: >10} KB",
                sys.used_memory() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "total swap:       {: >10} KB",
                sys.total_swap() / 1_000
            );
            writeln!(
                &mut io::stdout(),
                "used swap:        {: >10} KB",
                sys.used_swap() / 1_000
            );
        }
        "quit" | "exit" => return true,
        "all" => {
            for (pid, proc_) in sys.processes() {
                writeln!(
                    &mut io::stdout(),
                    "{}:{} status={:?}",
                    pid,
                    proc_.name().to_string_lossy(),
                    proc_.status()
                );
            }
        }
        "frequency" => {
            for cpu in sys.cpus() {
                writeln!(
                    &mut io::stdout(),
                    "[{}] {} MHz",
                    cpu.name(),
                    cpu.frequency(),
                );
            }
        }
        "vendor_id" => {
            writeln!(
                &mut io::stdout(),
                "vendor ID: {}",
                sys.cpus()[0].vendor_id()
            );
        }
        "brand" => {
            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
        }
        "load_avg" => {
            let load_avg = System::load_average();
            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
        }
        e if e.starts_with("show ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 2 {
                writeln!(
                    &mut io::stdout(),
                    "show command takes a pid or a name in parameter!"
                );
                writeln!(&mut io::stdout(), "example: show 1254");
            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
                match sys.process(pid) {
                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
                };
            } else {
                let proc_name = tmp[1];
                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
                    writeln!(
                        &mut io::stdout(),
                        "==== {} ====",
                        proc_.name().to_string_lossy()
                    );
                    writeln!(&mut io::stdout(), "{proc_:?}");
                }
            }
        }
        "temperature" => {
            for component in components.iter() {
                writeln!(&mut io::stdout(), "{component:?}");
            }
        }
        "network" => {
            for (interface_name, data) in networks.iter() {
                writeln!(
                    &mut io::stdout(),
                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
                    interface_name,
                    data.mac_address(),
                    data.received(),
                    data.total_received(),
                    data.transmitted(),
                    data.total_transmitted(),
                );
            }
        }
        "show" => {
            writeln!(
                &mut io::stdout(),
                "'show' command expects a pid number or a process name"
            );
        }
        e if e.starts_with("kill ") => {
            let tmp: Vec<&str> = e.split(' ').collect();

            if tmp.len() != 3 {
                writeln!(
                    &mut io::stdout(),
                    "kill command takes the pid and a signal number in parameter!"
                );
                writeln!(&mut io::stdout(), "example: kill 1254 9");
            } else {
                let pid = Pid::from_str(tmp[1]).unwrap();
                let signal = i32::from_str(tmp[2]).unwrap();

                if signal < 1 || signal > 31 {
                    writeln!(
                        &mut io::stdout(),
                        "Signal must be between 0 and 32 ! See the signals list with the \
                         signals command"
                    );
                } else {
                    match sys.process(pid) {
                        Some(p) => {
                            if let Some(res) =
                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
                            {
                                writeln!(&mut io::stdout(), "kill: {res}");
                            } else {
                                writeln!(
                                    &mut io::stdout(),
                                    "kill: signal not supported on this platform"
                                );
                            }
                        }
                        None => {
                            writeln!(&mut io::stdout(), "pid not found");
                        }
                    };
                }
            }
        }
        "disks" => {
            for disk in disks {
                writeln!(&mut io::stdout(), "{disk:?}");
            }
        }
        "users" => {
            for user in users {
                writeln!(
                    &mut io::stdout(),
                    "{:?} => {:?}",
                    user.name(),
                    user.groups()
                );
            }
        }
        "boot_time" => {
            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
        }
        "uptime" => {
            let up = System::uptime();
            let mut uptime = up;
            let days = uptime / 86400;
            uptime -= days * 86400;
            let hours = uptime / 3600;
            uptime -= hours * 3600;
            let minutes = uptime / 60;
            writeln!(
                &mut io::stdout(),
                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
            );
        }
        x if x.starts_with("refresh") => {
            if x == "refresh" {
                writeln!(&mut io::stdout(), "Getting processes' information...");
                sys.refresh_all();
                writeln!(&mut io::stdout(), "Done.");
            } else if x.starts_with("refresh ") {
                writeln!(&mut io::stdout(), "Getting process' information...");
                if let Some(pid) = x
                    .split(' ')
                    .filter_map(|pid| pid.parse().ok())
                    .take(1)
                    .next()
                {
                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
                    } else {
                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
                    }
                } else {
                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
                }
            } else {
                writeln!(
                    &mut io::stdout(),
                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
                     list.",
                );
            }
        }
        "pid" => {
            writeln!(
                &mut io::stdout(),
                "PID: {}",
                sysinfo::get_current_pid().expect("failed to get PID")
            );
        }
        "system" => {
            writeln!(
                &mut io::stdout(),
                "System name:              {}\n\
                 System kernel version:    {}\n\
                 System OS version:        {}\n\
                 System OS (long) version: {}\n\
                 System host name:         {}",
                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
            );
        }
        e => {
            writeln!(
                &mut io::stdout(),
                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
                 list.",
            );
        }
    }
    false
}
Source

pub fn cpu_arch() -> String

Returns the CPU architecture (eg. x86, amd64, aarch64, …).

Important: this information is computed every time this function is called.

use sysinfo::System;

println!("CPU Architecture: {:?}", System::cpu_arch());

Trait Implementations§

Source§

impl Debug for System

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for System

Source§

fn default() -> System

Returns the “default value” for a type. Read more
Source§

impl Serialize for System

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for System

§

impl RefUnwindSafe for System

§

impl Send for System

§

impl Sync for System

§

impl Unpin for System

§

impl UnwindSafe for System

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize = _

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.