Fundamentals 4 min read

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.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How Does Linux ‘top’ Gather System Metrics? A Deep Dive with strace

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 1

What 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.

LinuxSystem monitoringstracetop commandProc Filesystem
Java High-Performance Architecture
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.