Skip to content
systemcoding.dev
Systems Programming

Build a Process Monitor Like top by Reading /proc

Build a small top clone in C that reads /proc/PID/stat and /proc/stat on Linux 6.x, computes CPU percentages from tick deltas and sorts the busiest processes.

8 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, Linux and GNU logos.

top has no secret kernel interface. It opens text files under /proc, parses them, waits a second, reads them again and prints the difference. That is the whole trick, and it makes a process monitor one of the best small programs for learning how Linux exposes its state. This post builds one in C against Linux 6.x and glibc 2.41. It lists the busiest processes by CPU, shows resident memory and the command name, and refreshes on a timer. The field layout comes from the proc_pid_stat(5) man page and proc_stat(5), and every number in the program is read from there, not guessed. If directory walking is new, the earlier ls clone in this cluster shows opendir and readdir in detail.

Where the numbers come from

Three sources give you everything a basic monitor shows.

SourceWhat it holds
/proc/statThe first line, cpu, is total CPU time in clock ticks across all cores, split by state
/proc/PID/statOne line per process: state, utime, stime, rss, command name
/proc/PID/statmMemory sizes in pages, if you want something simpler than stat

A clock tick is 1 / sysconf(_SC_CLK_TCK) seconds, which is 100 on almost every Linux system. Times in these files are cumulative since boot or since the process started. A single read tells you nothing about current load. Only the difference between two reads, divided by the elapsed ticks of the whole machine, gives a percentage.

Parse /proc/PID/stat without being fooled by the name

The second field of /proc/PID/stat is the command name in parentheses, and that name can contain spaces and even other parentheses. A process called (sd-pam) or Web Content breaks any sscanf that splits on whitespace from the start. The reliable method is to find the last ) in the line with strrchr and parse the rest from there. After that closing parenthesis the fields are space separated and in a fixed order.

Counting from the state field (field 3 in the man page), the ones we need are:

  • state: field 3, one character such as R, S, Z

  • utime: field 14, user-mode ticks

  • stime: field 15, kernel-mode ticks

  • rss: field 24, resident set size in pages

Because we start parsing after the command name, the state is the first token and we skip tokens to reach field 14, 15 and 24.

procstat.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct proc_sample {
    int pid;
    char comm[64];
    char state;
    unsigned long long ticks;   /* utime + stime */
    long rss_pages;
};

int read_proc(int pid, struct proc_sample *out)
{
    char path[64], buf[2048];
    snprintf(path, sizeof path, "/proc/%d/stat", pid);

    FILE *f = fopen(path, "r");
    if (!f)
        return -1;                  /* the process exited: not an error */
    size_t n = fread(buf, 1, sizeof buf - 1, f);
    fclose(f);
    buf[n] = '\0';

    char *open = strchr(buf, '(');
    char *close = strrchr(buf, ')');
    if (!open || !close || close < open)
        return -1;

    size_t len = (size_t)(close - open - 1);
    if (len >= sizeof out->comm)
        len = sizeof out->comm - 1;
    memcpy(out->comm, open + 1, len);
    out->comm[len] = '\0';

    unsigned long long utime, stime;
    long rss;
    /* After ") " come fields 3 onward. Skip 10 (fields 4-13) with %*s. */
    int got = sscanf(close + 2,
        "%c %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %llu %llu "
        "%*s %*s %*s %*s %*s %*s %*s %*s %*s %ld",
        &out->state, &utime, &stime, &rss);
    if (got != 4)
        return -1;

    out->pid = pid;
    out->ticks = utime + stime;
    out->rss_pages = rss;
    return 0;
}

Count the skips: after the state (field 3) there are ten fields to skip (4 through 13), then utime and stime (14, 15), then nine to skip (16 through 23) and finally rss (24). The format string has exactly those. A process can vanish between readdir and fopen, so fopen failing is normal, and the function reports it with -1 and no message.

Read total CPU time

The first line of /proc/stat looks like cpu 4705 150 1120 16250 520 0 17 0 0 0, the columns being user, nice, system, idle, iowait, irq, softirq, steal, guest and guest_nice. The total for percentage purposes is the sum of the first eight. Guest time is already counted inside user time, so adding it would count it twice, which is stated in the man page.

cputotal.cc
#include <stdio.h>

unsigned long long read_total_ticks(void)
{
    FILE *f = fopen("/proc/stat", "r");
    if (!f)
        return 0;

    unsigned long long v[8] = {0};
    int got = fscanf(f, "cpu %llu %llu %llu %llu %llu %llu %llu %llu",
                     &v[0], &v[1], &v[2], &v[3],
                     &v[4], &v[5], &v[6], &v[7]);
    fclose(f);
    if (got < 4)
        return 0;

    unsigned long long total = 0;
    for (int i = 0; i < 8; i++)
        total += v[i];
    return total;
}

The percentage of one core's worth of machine time for a process is 100 * delta_proc_ticks / delta_total_ticks * ncpu, where ncpu comes from sysconf(_SC_NPROCESSORS_ONLN). top calls this Irix mode when it can exceed 100 on a multi-core machine. Multiplying by ncpu reproduces that view, and leaving it out gives the share of the whole machine.

Take two snapshots and sort

The monitor needs a table of samples, a second table a second later, and a join between them by pid. A process that appears only in the second snapshot is new and has no delta; one that appears only in the first has exited.

mytop.cc
#define _POSIX_C_SOURCE 200809L
#include <ctype.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

struct proc_sample {
    int pid;
    char comm[64];
    char state;
    unsigned long long ticks;
    long rss_pages;
};
int read_proc(int pid, struct proc_sample *out);
unsigned long long read_total_ticks(void);

struct row { struct proc_sample s; double cpu; };

static size_t snapshot(struct proc_sample **out)
{
    DIR *d = opendir("/proc");
    if (!d)
        return 0;
    size_t n = 0, cap = 256;
    struct proc_sample *v = malloc(cap * sizeof *v);
    struct dirent *e;
    while ((e = readdir(d)) != NULL) {
        if (!isdigit((unsigned char)e->d_name[0]))
            continue;
        if (n == cap) {
            cap *= 2;
            v = realloc(v, cap * sizeof *v);
        }
        if (read_proc(atoi(e->d_name), &v[n]) == 0)
            n++;
    }
    closedir(d);
    *out = v;
    return n;
}

static int by_cpu(const void *a, const void *b)
{
    double x = ((const struct row *)a)->cpu, y = ((const struct row *)b)->cpu;
    return (x < y) - (x > y);
}

int main(void)
{
    long page_kb = sysconf(_SC_PAGESIZE) / 1024;
    long ncpu = sysconf(_SC_NPROCESSORS_ONLN);

    struct proc_sample *a, *b;
    unsigned long long t0 = read_total_ticks();
    size_t na = snapshot(&a);
    sleep(1);
    unsigned long long t1 = read_total_ticks();
    size_t nb = snapshot(&b);

    double dt = (double)(t1 - t0);
    struct row *rows = calloc(nb, sizeof *rows);
    for (size_t i = 0; i < nb; i++) {
        rows[i].s = b[i];
        for (size_t j = 0; j < na; j++) {
            if (a[j].pid == b[i].pid) {
                rows[i].cpu = dt > 0
                    ? 100.0 * ncpu * (double)(b[i].ticks - a[j].ticks) / dt
                    : 0.0;
                break;
            }
        }
    }
    qsort(rows, nb, sizeof *rows, by_cpu);

    printf("%7s %5s %9s %c %s\n", "PID", "%CPU", "RSS(KiB)", 'S', "COMMAND");
    for (size_t i = 0; i < nb && i < 5; i++)
        printf("%7d %5.1f %9ld %c %s\n", rows[i].s.pid, rows[i].cpu,
               rows[i].s.rss_pages * page_kb, rows[i].s.state, rows[i].s.comm);
    return 0;
}

Build with cc -std=c11 -Wall -O2 -o mytop mytop.c procstat.c cputotal.c. On a four-core machine with one compile job running, the output looks like the block below. The pids and numbers will differ on yours.

Text
    PID  %CPU  RSS(KiB) S COMMAND
  48211  97.0     61240 R cc1
   1893   2.0    412880 S firefox
   2304   1.0     88104 S Xorg
      1   0.0     13420 S systemd
   1247   0.0      5208 S sshd

Make it loop like top

To refresh, wrap the snapshot logic in a loop and reuse the second snapshot as the first of the next round. That avoids rereading /proc twice per cycle, and it keeps the time between samples equal to the sleep. Clear the screen with the escape sequence "\033[H\033[2J" before each print. Terminal handling beyond that, such as keys to quit, needs raw mode, which the text editor post in this cluster builds.

Where the numbers mislead

  • Threads. /proc/PID/stat aggregates the whole thread group. To show threads, read /proc/PID/task/TID/stat.

  • Zombie and exited processes. A zombie has state Z and zero RSS. Its ticks stop growing, and it is gone from the next snapshot after the parent reaps it.

  • Pid reuse. If a pid exits and is reused within the second, the join matches two different programs. Comparing the starttime field (field 22) in both snapshots removes the false match.

  • CPU hotplug and containers. sysconf(_SC_NPROCESSORS_ONLN) ignores cgroup CPU limits. Inside a container, /proc/stat still shows host totals, so percentages are relative to the host.

Why the first sample is not enough

A newcomer's first instinct is to print utime + stime for each process and sort. That list is real, but it answers a different question: which processes have used the most CPU since they started. A shell that has run for three weeks and compiled a lot will outrank a runaway loop that began a minute ago, even though the loop is the thing eating your machine right now. Current load is a rate, and a rate needs two points in time.

The same reasoning applies to the denominator. The kernel counts ticks per CPU state in /proc/stat, and those counters only grow. Dividing a process's tick delta by the wall-clock seconds works if the tick rate is exactly 100 per second and the sleep was exactly one second, but neither is guaranteed. Dividing by the delta of total ticks removes both assumptions, because the numerator and denominator are measured by the same counters over the same interval, whatever its length.

Extending the monitor

Once the two-snapshot structure exists, most features are small additions. To show the user name, stat the file /proc/PID and read st_uid, then look it up with getpwuid, exactly as the ls clone does. To show the full command line instead of the 15-character name in stat, read /proc/PID/cmdline, which holds the arguments separated by NUL bytes. To show memory as a percentage, read MemTotal from /proc/meminfo and divide the resident size by it. To add a quit key, put the terminal in raw mode as the text editor post does and poll with select or poll using the refresh interval as the timeout, so a keypress interrupts the wait.

Be careful with /proc/PID/cmdline for kernel threads. It is empty, and the right fallback is the name in brackets that top prints, which is the comm field wrapped in square brackets. Be careful too about reading files of other users: most of /proc/PID/stat is world-readable, but /proc/PID/io and /proc/PID/environ are not, and hidepid mount options can hide other users' directories entirely, in which case your snapshot lists only your own processes.

Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, GNU and Rust logos.
Systems Programming

Build an ls Clone with Long Listing Output

Build an ls -l clone in C with opendir, readdir and lstat: mode strings, owner names, sizes and timestamps, using POSIX.1-2024 calls on Linux with glibc 2.41.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.