Project 13: Mini-htop Clone

Build an interactive process monitor with sorting, filtering, and signals.

Quick Reference

Attribute Value
Difficulty Expert
Time Estimate 1-2 months
Language C (Alternatives: Rust, Go)
Prerequisites Projects 1-12
Key Topics /proc parsing, CPU% math, TUI design

1. Learning Objectives

By completing this project, you will:

  1. Parse process data from /proc at scale.
  2. Calculate CPU% and memory% accurately over time.
  3. Build a terminal UI with sorting and filtering.
  4. Send signals interactively to selected processes.

2. Theoretical Foundation

2.1 Core Concepts

  • Sampling for CPU%: Requires two snapshots of process and total CPU time.
  • Process trees: Parent-child relationships form the tree view.
  • TUI rendering: Efficient screen redraw with minimal flicker.

2.2 Why This Matters

This capstone forces you to integrate all system tool knowledge into one cohesive program.

2.3 Historical Context / Background

top and htop are classic Unix tools; building your own shows deep mastery of Linux process internals.

2.4 Common Misconceptions

  • “CPU% is instantaneous”: It is a rate over time.
  • “TUI is just printf”: It requires screen buffering and key handling.

3. Project Specification

3.1 What You Will Build

A full-screen terminal UI that lists processes with PID, user, CPU%, MEM%, time, and command, supports sorting/filtering, and allows sending signals.

3.2 Functional Requirements

  1. Display process list with CPU% and MEM%.
  2. Support sorting by CPU, MEM, PID.
  3. Provide filter/search input.
  4. Send signals (TERM/KILL) to a selected process.
  5. Refresh at a fixed interval.

3.3 Non-Functional Requirements

  • Performance: Handle hundreds of processes smoothly.
  • Reliability: Handle process churn without crashing.
  • Usability: Keyboard shortcuts and clear status bar.

3.4 Example Usage / Output

$ ./mini-htop
PID  USER  CPU%  MEM%  TIME   COMMAND
1234 user  45.2  1.0   12:34  python3 server.py

3.5 Real World Outcome

You will open the UI and navigate processes, sort by CPU or memory, and send signals. Example:

$ ./mini-htop
PID  USER  CPU%  MEM%  TIME   COMMAND
1234 user  45.2  1.0   12:34  python3 server.py

4. Solution Architecture

4.1 High-Level Design

/proc scan -> compute metrics -> render TUI -> handle input -> update loop

4.2 Key Components

Component Responsibility Key Decisions
Proc scanner Read per-PID data Cache previous samples
Metrics CPU% and MEM% Use jiffies + total CPU time
UI Render and handle keys ncurses or termios
Actions Send signals Use kill(2)

4.3 Data Structures

struct ProcInfo { int pid; char comm[64]; double cpu; double mem; };

4.4 Algorithm Overview

Key Algorithm: CPU% Calculation

  1. Read per-PID utime+stime and total cpu time.
  2. Sleep interval.
  3. Compute deltas and CPU%.

Complexity Analysis:

  • Time: O(n) per refresh
  • Space: O(n) process cache

5. Implementation Guide

5.1 Development Environment Setup

gcc --version

5.2 Project Structure

project-root/
├── src/
│   ├── main.c
│   ├── proc_scan.c
│   ├── ui.c
│   └── metrics.c
├── include/
└── README.md

5.3 The Core Question You’re Answering

“How do I build a real-time view of the system that matches how the kernel sees it?”

5.4 Concepts You Must Understand First

Stop and research these before coding:

  1. /proc fields
  2. Jiffies and CPU accounting
  3. Terminal input/output control

5.5 Questions to Guide Your Design

Before implementing, think through these:

  1. How will you handle terminal resize?
  2. How will you compute CPU% for short-lived processes?
  3. How will you keep rendering fast?

5.6 Thinking Exercise

Compare with htop

Run htop and list the features you want in your minimal clone. Pick a small subset.

5.7 The Interview Questions They’ll Ask

Prepare to answer these:

  1. “How is CPU% calculated for a process?”
  2. “How does /proc expose process data?”
  3. “How do you avoid flicker in a TUI?”

5.8 Hints in Layers

Hint 1: Start with a table Render a static table before adding live updates.

Hint 2: Cache previous values Store utime+stime per PID for delta calculations.

Hint 3: Limit redraws Clear and redraw only changed rows if possible.

5.9 Books That Will Help

Topic Book Chapter
/proc and processes “TLPI” Ch. 12, 26
Terminal control “APUE” Ch. 18
Performance tools “Systems Performance” Ch. 6

5.10 Implementation Phases

Phase 1: Foundation (2 weeks)

Goals:

  • Parse /proc and compute CPU/mem.

Tasks:

  1. Read /proc//stat and /proc/stat.
  2. Compute CPU% and MEM%.

Checkpoint: Values match top within tolerance.

Phase 2: Core Functionality (2-3 weeks)

Goals:

  • Build TUI and update loop.

Tasks:

  1. Render list in ncurses.
  2. Add refresh loop.

Checkpoint: UI refreshes without flicker.

Phase 3: Polish & Edge Cases (2-3 weeks)

Goals:

  • Add sorting, filtering, and signals.

Tasks:

  1. Implement sort keys.
  2. Add search/filter input.
  3. Add signal actions.

Checkpoint: You can sort and kill a process interactively.

5.11 Key Implementation Decisions

Decision Options Recommendation Rationale
UI library ncurses vs raw termios ncurses Faster to build
Refresh rate 1s vs 2s 1s Feels responsive

6. Testing Strategy

6.1 Test Categories

Category Purpose Examples
Metrics Validate CPU% Compare with top
UI Validate rendering Resize terminal
Actions Validate signals Send SIGTERM

6.2 Critical Test Cases

  1. CPU% matches top within reasonable tolerance.
  2. UI handles terminal resize gracefully.
  3. Signal actions target correct PID.

6.3 Test Data

PID sample: 1 (systemd)

7. Common Pitfalls & Debugging

7.1 Frequent Mistakes

Pitfall Symptom Solution
Wrong stat parsing Bad CPU% Handle comm field with parentheses
Single-sample CPU% 0 or spikes Use deltas
UI flicker Unreadable screen Use double-buffering

7.2 Debugging Strategies

  • Log raw parsed values to a file.
  • Compare CPU% with top for a stable process.

7.3 Performance Traps

Full screen redraws at high frequency can be expensive; reduce refresh rate if needed.


8. Extensions & Challenges

8.1 Beginner Extensions

  • Add a help screen with key bindings.
  • Add process tree toggle.

8.2 Intermediate Extensions

  • Add per-user filtering.
  • Add column resizing.

8.3 Advanced Extensions

  • Add thread view.
  • Add config file for defaults.

9. Real-World Connections

9.1 Industry Applications

  • Building custom monitoring UIs for specialized systems.
  • htop: https://htop.dev
  • btop: https://github.com/aristocratos/btop

9.3 Interview Relevance

  • Demonstrates deep knowledge of /proc and performance monitoring.

10. Resources

10.1 Essential Reading

  • proc(5) - man 5 proc
  • ncurses(3) - man 3 ncurses

10.2 Video Resources

  • Terminal UI tutorials (search “ncurses tutorial”)

10.3 Tools & Documentation

  • kill(2) - man 2 kill

11. Self-Assessment Checklist

11.1 Understanding

  • I can explain CPU% calculations.
  • I can parse /proc correctly.
  • I can render a stable terminal UI.

11.2 Implementation

  • UI refreshes smoothly.
  • Sorting/filtering works.
  • Signals are sent safely.

11.3 Growth

  • I can compare my tool with htop and explain differences.
  • I can extend with new views.

12. Submission / Completion Criteria

Minimum Viable Completion:

  • Display processes with CPU% and MEM% in a TUI.

Full Completion:

  • Add sorting, filtering, and signal actions.

Excellence (Going Above & Beyond):

  • Add tree view and thread view with configurable layout.

This guide was generated from LINUX_SYSTEM_TOOLS_MASTERY.md. For the complete learning path, see the parent directory.