How Does htop Read Metrics From /proc?

The htop command-line utility is a staple for Linux system administrators, offering a real-time, interactive overview of system resources like CPU usage, memory consumption, and running processes. Unlike static tools, htop achieves its dynamic monitoring by continuously parsing virtual files within the /proc filesystem—a pseudo-filesystem generated on the fly by the Linux kernel. This article explores how htop translates these raw, text-based kernel metrics into an intuitive, color-coded terminal interface.

The Pseudo-Filesystem as a Data Source

In Linux, the /proc directory does not contain actual files stored on a disk; instead, it acts as an interface to the Linux kernel’s internal data structures. When htop requests information, the kernel generates text outputs representing the current state of the system.

htop specifically targets several key files to populate its main dashboard:

Tracking Individual Processes

To populate the detailed process list at the bottom of the screen, htop scans the numbered directories within /proc. Each number corresponds to a specific Process ID (PID) currently running on the system.

For every PID directory, htop opens and reads several specific files:

The Read-and-Refresh Cycle

Because system metrics change every millisecond, htop operates in a continuous loop dictated by its refresh interval (defaulting to every 1.5 seconds). During each cycle, the utility clears its internal data structures, performs rapid read operations across the necessary /proc files, and calculates differences between the current data and the data from the previous cycle.

For example, to calculate the CPU percentage shown in the bars, htop cannot rely on a single snapshot from /proc/stat. It must take two reads separated by time, calculate the delta of total CPU time versus idle CPU time, and convert that ratio into a percentage. Once these calculations are complete, htop uses the ncurses library to efficiently redraw only the parts of the terminal screen that have changed, ensuring minimal CPU overhead from the monitoring tool itself.