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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Piping a child's stdout into a BufReader lets you process command output as a stream of lines rather than one big string.
- 2An immediately-invoked closure returning Option lets you chain fallible parses with ? and skip any row that doesn't fully parse.
- 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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-ps-output-into-structs-in-rust-explained-rust-889c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.