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
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 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.