Write a pure-rust implementation of px (https://github.com/genotrance/px)
- User
Write a pure-rust implementation of px (https://github.com/genotrance/px)
- Assistant
Write a pure-rust implementation of px (https://github.com/genotrance/px)
Creating a pure Rust implementation of px—a terminal-based process monitor—can be an exciting project. Below, I’ll guide you through building a simplified version of px using Rust. This implementation will display a list of running processes with their CPU and memory usage in a terminal-based user interface.
We'll use the following Rust crates to facilitate development:
sysinfo: To retrieve system and process information.tui and crossterm: To build the terminal user interface.Initialize a New Cargo Project
cargo new px-rs
cd px-rs
Add Dependencies
Update your Cargo.toml with the necessary dependencies:
[dependencies]
sysinfo = { version = "0.28", features = ["refresh_cpu"] }
tui = "0.20"
crossterm = "0.26"
anyhow = "1.0"
sysinfo: For accessing system and process information.tui and crossterm: For building the terminal UI.anyhow: For simple error handling.Create the main application in src/main.rs:
use std::error::Error;
use std::io;
use sysinfo::{ProcessExt, System, SystemExt};
use tui::{
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::{Span, Spans},
widgets::{Block, Borders, Cell, Row, Table},
Terminal,
};
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use std::time::{Duration, Instant};
use std::thread;
struct App {
system: System,
}
impl App {
fn new() -> App {
let mut system = System::new_all();
system.refresh_all();
App { system }
}
fn update(&mut self) {
self.system.refresh_all();
}
}
fn main() -> Result<(), Box<dyn Error>> {
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Create app and run it
let app = App::new();
let res = run_app(&mut terminal, app);
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
if let Err(err) = res {
println!("{:?}", err)
}
Ok(())
}
fn run_app<B: tui::backend::Backend>(
terminal: &mut Terminal<B>,
mut app: App,
) -> Result<(), Box<dyn Error>> {
let tick_rate = Duration::from_secs(2);
let mut last_tick = Instant::now();
loop {
terminal.draw(|f| ui(f, &app))?;
let timeout = tick_rate
.checked_sub(last_tick.elapsed())
.unwrap_or_else(|| Duration::from_secs(0));
if event::poll(timeout)? {
if let Event::Key(key) = event::read()? {
if key.code == KeyCode::Char('q') {
return Ok(());
}
}
}
if last_tick.elapsed() >= tick_rate {
app.update();
last_tick = Instant::now();
}
}
}
fn ui<B: tui::backend::Backend>(f: &mut tui::Frame<B>, app: &App) {
// Create a block with border
let block = Block::default().title("px-rs").borders(Borders::ALL);
f.render_widget(block, f.size());
// Create table rows
let processes: Vec<_> = app
.system
.processes()
.iter()
.map(|(_, proc)| {
Row::new(vec![
proc.name().to_string(),
proc.pid().to_string(),
format!("{:.2}%", proc.cpu_usage()),
format!("{:.2} MB", proc.memory() as f64 / 1024.0),
])
})
.collect();
// Define table headers
let table = Table::new(processes)
.header(
Row::new(vec!["Name", "PID", "CPU%", "Memory"])
.style(Style::default().fg(Color::Yellow))
.bottom_margin(1),
)
.block(Block::default().borders(Borders::ALL).title("Processes"))
.widths(&[
Constraint::Percentage(40),
Constraint::Percentage(15),
Constraint::Percentage(15),
Constraint::Percentage(30),
])
.column_spacing(1)
.highlight_style(Style::default().add_modifier(Modifier::BOLD))
.highlight_symbol(">> ");
// Split the terminal area into chunks
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(1)
.constraints([Constraint::Percentage(100)].as_ref())
.split(f.size());
f.render_widget(table, chunks[0]);
}
Terminal Setup: The application switches the terminal to raw mode and enters the alternate screen to have full control over the terminal display without affecting the main shell.
App State: The App struct holds the system information. It initializes by refreshing all system data.
Event Loop: The run_app function contains the main event loop, which:
User Interface:
Graceful Shutdown: Upon exiting, the terminal is restored to its original state, ensuring no lingering side effects.
The above implementation is a basic prototype. Here are several enhancements you can implement to make it more feature-complete and closer to px:
Sorting: Allow sorting processes by CPU usage, memory, PID, etc.
Filtering: Implement search or filter functionality to find specific processes.
Interactive Controls: Enable actions like killing a process, renicing, or sending signals.
Dynamic Updating: Improve the UI to handle real-time updates more smoothly.
Enhanced UI: Add more visual elements like sparklines for CPU usage over time or bar charts for memory consumption.
Cross-Platform Support: Ensure the application works seamlessly across different operating systems.
sysinfo Documentationtui Documentationcrossterm DocumentationThis guide provides a foundational approach to building a px-like application in Rust. By leveraging powerful crates like sysinfo and tui, you can create robust and efficient terminal-based applications. Expand upon this foundation by adding features and refining the UI to suit your needs.
Feel free to ask if you need further assistance or have specific questions about extending this implementation!
Not yet included in a published release.