AlgoViz

How the Linux kernel works

medium 40 min

The kernel is the one program that runs with full privilege.

A toy kernel runs cat

Read it, run it, change a line and run it again.

Loading editor…

Runs here. A tiny model of one cat command: a system call door, fork, a run queue with virtual time, a dentry cache, a page cache and a slow disk. All costs are made-up microseconds, chosen only to show where time goes.

The same in c
/* mycat.c: the same work as cat, with the system calls in plain sight.   Build and trace on Linux:  cc -O2 -o mycat mycat.c && strace ./mycat /etc/hostname */#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <string.h>#include <unistd.h>int main(int argc, char **argv) {    if (argc != 2) {        fprintf(stderr, "usage: %s FILE\n", argv[0]);        return 2;    }    int fd = open(argv[1], O_RDONLY | O_CLOEXEC);        /* openat: VFS path walk, new file object */    if (fd < 0) {        fprintf(stderr, "open: %s\n", strerror(errno));   /* the wrapper returned -1 and set errno */        return 1;    }    char buf[65536];    for (;;) {        ssize_t n = read(fd, buf, sizeof buf);            /* page cache copy, or sleep in D for the disk */        if (n == 0) break;                                 /* end of file */        if (n < 0) {            if (errno == EINTR) continue;                  /* a signal arrived: try again */            perror("read");            return 1;        }        for (ssize_t done = 0; done < n;) {            ssize_t w = write(STDOUT_FILENO, buf + done, n - done);  /* tty, pipe or socket: same call */            if (w < 0) {                if (errno == EINTR) continue;                perror("write");                return 1;            }            done += w;                                     /* a write may take fewer bytes than asked */        }    }    close(fd);    return 0;                                              /* exit_group; the shell reaps us with wait */}
The same in Shell
#!/usr/bin/env bash# A five-minute tour of the kernel from the command line. Read-only; strace and perf may need installing or root.set -uecho "kernel: $(uname -r)"echo "--- this shell, as the kernel sees it"grep -E '^(Name|State|Threads|VmRSS|voluntary_ctxt|nonvoluntary_ctxt)' /proc/$$/statusls -l /proc/$$/fdecho "--- namespaces and cgroup of this shell"ls -l /proc/$$/nscat /proc/$$/cgroupecho "--- load: R and D tasks; pressure: time lost waiting"cat /proc/loadavgcat /proc/pressure/cpu /proc/pressure/io 2>/dev/nullecho "--- kernel threads (names in brackets)"ps -eo pid,ppid,stat,cmd | awk '$2 == 2' | head -5echo "--- interrupts and switches per second for 3 seconds"vmstat 1 3if command -v strace >/dev/null; then  echo "--- system calls of ls, counted"  strace -c -o /dev/stderr ls / > /dev/nullfiif command -v perf >/dev/null; then  echo "--- faults and switches of one command"  perf stat -e page-faults,context-switches ls / > /dev/nullfi