rust 45 lines · 8 steps

Parsing ps output into structs in Rust

Spawn the ps command, stream its output line by line, and turn each row into a sorted list of top processes.

Explained by highlit
1use std::io::{BufRead, BufReader};
2use std::process::{Command, Stdio};
3 
4#[derive(Debug)]
5struct Process {
6 pid: u32,
7 cpu: f64,
8 mem: f64,
9 command: String,
10}
11 
12fn top_processes(limit: usize) -> std::io::Result<Vec<Process>> {
13 let mut child = Command::new("ps")
14 .args(["axo", "pid,pcpu,pmem,comm"])
15 .stdout(Stdio::piped())
16 .spawn()?;
17 
18 let stdout = child.stdout.take().expect("stdout was piped");
19 let reader = BufReader::new(stdout);
20 
21 let mut processes = Vec::new();
22 for line in reader.lines().skip(1) {
23 let line = line?;
24 let mut fields = line.split_whitespace();
25 
26 let parsed = (|| {
27 Some(Process {
28 pid: fields.next()?.parse().ok()?,
29 cpu: fields.next()?.parse().ok()?,
30 mem: fields.next()?.parse().ok()?,
31 command: fields.collect::<Vec<_>>().join(" "),
32 })
33 })();
34 
35 if let Some(proc) = parsed {
36 processes.push(proc);
37 }
38 }
39 
40 child.wait()?;
41 
42 processes.sort_by(|a, b| b.cpu.total_cmp(&a.cpu));
43 processes.truncate(limit);
44 Ok(processes)
45}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Piping a child's stdout into a BufReader lets you process command output as a stream of lines rather than one big string.
  2. 2An immediately-invoked closure returning Option lets you chain fallible parses with ? and skip any row that doesn't fully parse.
  3. 3total_cmp gives a total ordering over f64 so you can sort floating-point fields without wrapping them or handling NaN by hand.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing ps output into structs in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code