# Htop Clone System Monitor - C Implementation Specification - rtop ## Project Overview Create a terminal-based system monitoring tool in C that replicates htop's visual interface and functionality. The tool displays comprehensive system statistics in a dynamic, auto-refreshing interface with no external dependencies or interactive actions. The application name will be `rtop`. ## Core Requirements ### Language & Constraints - Implementation language: C (C99 or later) - No external library dependencies beyond standard C library - Single binary compilation with no runtime dependencies - Statically linked where possible - Cross-platform Linux support (primary focus: Linux kernel interfaces) ### Data Sources All system information must be read directly from: - `/proc` filesystem (process information, CPU stats, memory) - `/sys` filesystem (system-wide metrics) - Standard C library system calls (sysconf, getrlimit, etc.) - `/etc` system files (hostname, OS information) ## Display Requirements ### Terminal Interface - Auto-refreshing display (configurable interval, default 1-2 seconds) - Full-screen terminal rendering using raw terminal control - Handle terminal resize events gracefully - Color support for visual differentiation - UTF-8 character support for borders and separators ### Information Categories #### System Overview Section - Hostname and kernel version - Uptime (days, hours, minutes) - Current date and time - Load averages (1, 5, 15 minute) - System architecture #### CPU Information - Total CPU count and logical cores - Per-core utilization percentages - Aggregate CPU usage - CPU frequency (current, min, max if available) - CPU temperature (if available from thermal zones) - Context switches per second - Interrupts per second #### Memory & Swap - Total physical memory - Used and available memory - Memory utilization percentage - Cached and buffered memory - Swap total, used, free - Swap utilization percentage - Page faults and page in/out statistics #### Process Statistics - Total process count - Running processes - Sleeping processes - Zombie/defunct processes - Stopped processes #### I/O Statistics - Disk read/write operations per second - Disk bytes read/written per second - I/O wait time percentage - Network statistics (if available): bytes in/out, packets #### Process Table - Scrollable list of running processes (or top N processes) - Per-process information: - Process ID (PID) - Parent PID (PPID) - User (UID or username) - CPU usage percentage - Memory usage percentage and absolute (RSS) - Virtual memory size (VSZ) - Process state (running, sleeping, zombie, etc.) - Command name and arguments (or executable path) - Thread count - Priority/Nice value #### Network Information - Interface names and states - IP addresses (IPv4) - RX/TX bytes and packets - Network errors and dropped packets #### Filesystem Statistics - Mount points and filesystems - Total, used, available space per mount - Utilization percentage - Filesystem type ## Interface Layout ### Header Section Display system overview with high-level metrics in a compact, scannable format. ### Metrics Panels Organize information into logical sections: - CPU and thermal metrics - Memory and swap usage - Process counts and states - Network and I/O throughput - Filesystem usage ### Process List Table format showing top processes by CPU or memory usage, with sortable columns and clear visual hierarchy. ### Footer Display refresh rate, current timestamp, and interaction hints (if applicable). ## Rendering Approach ### Terminal Control - Use standard ANSI escape codes for cursor positioning, colors, and formatting - Implement double-buffering to prevent flicker - Clear and redraw entire screen on each refresh cycle - Handle terminal capabilities detection ### Performance Considerations - Minimize system calls per refresh cycle - Cache system information that doesn't change frequently - Read `/proc` efficiently (sequential parsing) - Update only changed values in display - Target <5% CPU usage for the monitor itself ### Color Scheme - Define a readable color palette using standard terminal colors (16-color or 256-color) - Use colors to highlight: - High utilization (red threshold) - Medium utilization (yellow threshold) - Normal ranges (green) - Neutral information (white/default) ## Configuration & Behavior ### Default Behavior - Refresh interval: 1-2 seconds (user-adjustable via command-line argument or config) - Start with full system view - Sort processes by CPU usage by default (or memory alternative) - Display processes in descending utilization order ### Graceful Shutdown - Clean terminal state on exit (restore cursor visibility, reset colors) - Handle SIGINT (Ctrl+C) for clean termination - Restore terminal to pre-execution state ### Edge Cases - Handle systems with unusual core counts (single-core, high-core systems) - Support systems with limited `/proc` filesystem features - Gracefully degrade missing data sources - Handle rapid terminal resizing without crashing ## Data Update Strategy ### Sampling Approach - Read all system metrics at regular intervals (matching refresh rate) - Calculate deltas for rate-based metrics (I/O operations, network traffic) - Maintain rolling history for trend calculation if needed ### Metric Calculation - CPU usage: derived from `/proc/stat` (user, system, idle times) - Memory: from `/proc/meminfo` - Process metrics: from `/proc/[pid]/stat`, `/proc/[pid]/status` - I/O: from `/proc/diskstats` and `/proc/net/dev` ## Compilation & Deployment ### Build Requirements - Standard C compiler (gcc, clang) - Produces single static binary (or minimal dynamic linking) - No configuration files required at runtime - No installation script needed ### Binary Size & Performance - Target executable size: <2MB - Startup time: <100ms - Refresh cycle: <100ms per iteration - Memory footprint: <10MB RSS during operation ## Documentation The tool should be self-documenting through: - Clear, logical screen layout - Labeled sections and columns - Metric units displayed inline - Help text on startup or in footer ## Success Criteria - Displays 20+ distinct system metrics simultaneously - Updates smoothly at regular intervals - Survives 1+ hour continuous operation without memory leaks - Responsive to terminal size changes - No dependencies beyond libc - Compiles cleanly with `-Wall -Wextra -std=c99` - Provides useful system overview at a glance comparable to htop