How Does Linux ‘top’ Gather System Metrics? A Deep Dive with strace
Using strace to trace the Linux ‘top’ command reveals that it reads a wealth of system information from the virtual /proc filesystem, where files like cpuinfo, meminfo, stat, and others provide real‑time metrics that power top’s monitoring display.
top is a crucial Linux command for quickly viewing system status. To understand how top obtains various metrics, we can trace its execution with strace.
strace -o /tmp/strace_top.txt top -b -n 1What strace does
In Linux, a process cannot directly access hardware devices; it must switch from user mode to kernel mode via system calls. strace records the system calls made by a process.
The above command saves top’s execution trace to a file.
Viewing the file: vim /tmp/strace_top.txt The file is large and complex, but a pattern emerges: top opens, reads, analyzes, and closes many files, especially under the virtual /proc filesystem.
/proc is a virtual filesystem created by the Linux kernel in memory, not stored on disk. Its directory structure includes entries such as:
/proc
|--/version
|--/fs
|--/stat
|--...
|--/N/stat
|--/N/mem
|--/N/fs
|--/N/...Files under /proc contain system information. Each /proc/N directory is named after a process ID (PID) and holds that process’s data.
Examples of important files:
/proc/cpuinfo : CPU hardware details (model, speed, cores, cache).
/proc/meminfo : Memory statistics (total, free, swap).
/proc/stat : CPU activity states.
/proc/diskstats : Disk information.
/proc/loadavg : Load averages derived from recent CPU and I/O activity.
/proc/N/fd : File descriptors of the process.
/proc/N/mem : Memory held by the process (not readable).
/proc/N/stat : Process status, including user and kernel time, address space sizes, parent PID, thread group ID, etc.
The rich data in /proc serves as the primary source for monitoring commands and tools like top.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
