TExcelTAD

/proc & /sys

Linux exposes a huge amount of kernel state as files. Under /proc you can read the memory map of any of your processes, the list of mounted file systems or the CPU's features; under /sys you can see every device and driver; and by writing to some of those files, an administrator can change kernel settings at runtime. None of these files exist on a disk: the kernel generates their contents at the moment you read them. Tools like ps, top, free, lsblk and ip are mostly just friendly readers of /proc and /sys.

text
 cat /proc/meminfo
     |
     v  open() + read()
   VFS  ---> procfs driver ---> asks the memory manager for current numbers,
                                formats them as text, returns them as "file content"

Both are mounted at boot as virtual file systems (proc and sysfs, see Linux File Systems). A quick way to see they are not ordinary files: they report a size of 0 bytes, yet cat prints plenty.

bash · try it yourself
stat -c '%s bytes  %n' /proc/meminfo /proc/version /proc/sys/kernel/ostype
wc -l < /proc/meminfo | awk '{print ($1 > 10 ? "more than 10 lines" : "few lines") " when read"}'
cat /proc/sys/kernel/ostype
0 bytes  /proc/meminfo
0 bytes  /proc/version
0 bytes  /proc/sys/kernel/ostype
more than 10 lines when read
Linux

/proc/<pid>: one directory per process

Every running process has a directory named after its PID, and /proc/self is a magic link to the directory of whoever is reading it. So cat /proc/self/comm prints cat, because cat is the process doing the reading:

bash · try it yourself
cat /proc/self/comm
read -r name < /proc/self/comm; echo "$name"    # read is a bash builtin, so the reader is bash
grep -E '^(Name|State|Uid|Gid|Threads)' /proc/self/status
readlink /proc/self/cwd
cat
bash
Name:	grep
State:	R (running)
Uid:	1000	1000	1000	1000
Gid:	1000	1000	1000	1000
Threads:	1
/home/learner

The four numbers after Uid: are the real, effective, saved and file-system user IDs; they differ only for setuid programs (Linux Users & Permissions).

The most useful entries in /proc/<pid>/:

Entry Contains
comm, cmdline Program name; full command line (arguments separated by NUL bytes)
status Human-readable summary: state, PIDs, user IDs, memory (VmRSS), threads, capabilities
stat The same as one line of numbers, for programs (ps parses it)
environ Environment variables at start-up (NUL-separated, readable only by the owner)
cwd, exe, root Symlinks to the working directory, the executable, the root directory
fd/ One symlink per open file descriptor
maps, smaps Memory regions: code, heap, stack, shared libraries (Virtual Memory & Paging)
limits Resource limits (ulimit)
ns/, cgroup Namespaces and cgroup: the container the process lives in
oom_score_adj How eagerly the out-of-memory killer picks this process

Let's inspect a background process from the outside, the way ps and lsof do:

bash · try it yourself
sleep 30 &
pid=$!
sleep 0.2                                   # give it time to exec
echo "comm:    $(cat /proc/$pid/comm)"
echo "cmdline: $(tr '\0' ' ' < /proc/$pid/cmdline)"
grep '^State' /proc/$pid/status
[ "$(awk '/^PPid/ {print $2}' /proc/$pid/status)" = "$" ] && echo "its parent is this shell"

exec 3> notes.txt                           # open a file on descriptor 3 of this shell
echo "fd 3 ->  $(readlink /proc/$/fd/3)"
GREETING=hello cat /proc/self/environ | tr '\0' '\n' | grep '^GREETING='
kill $pid
comm:    sleep
cmdline: sleep 30 
State:	S (sleeping)
its parent is this shell
fd 3 ->  /home/learner/notes.txt
GREETING=hello

S (sleeping) means the process is waiting for something (here a timer), not using the CPU. Other states you will see are R running, D uninterruptible disk wait, T stopped and Z zombie (see Processes).

System-wide information in /proc

File Shows Read by
/proc/cpuinfo Each CPU: model, flags (vmx, avx2), MHz lscpu
/proc/meminfo Total, free, available, cached, swap free
/proc/loadavg Load averages, running/total threads, last PID uptime
/proc/stat CPU time counters since boot top, vmstat
/proc/uptime Seconds since boot uptime
/proc/mounts Mounted file systems (link to self/mounts) findmnt, df
/proc/filesystems File system types the kernel supports mount
/proc/modules Loaded kernel modules lsmod
/proc/cmdline The kernel's boot command line —
/proc/interrupts Interrupt counts per CPU and device —
/proc/pressure/ Pressure stall information: how long tasks waited for CPU, memory, I/O systemd-oomd

These counters are cumulative, so tools take two snapshots and compare them. Here is how top turns the first line of /proc/stat into a CPU-usage percentage (the numbers are clock ticks since boot, two samples taken one second apart):

python · try it yourself
sample1 = "cpu  4705 150 1120 1644000 2400 0 25 0 0 0"
sample2 = "cpu  4790 150 1150 1644365 2405 0 25 0 0 0"
fields = ["user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal"]

def parse(line):
    return dict(zip(fields, map(int, line.split()[1:9])))

a, b = parse(sample1), parse(sample2)
delta = {k: b[k] - a[k] for k in fields}
total = sum(delta.values())
idle = delta["idle"] + delta["iowait"]
print("ticks in the interval:", total)
for k in ("user", "system", "idle", "iowait"):
    print(f"  {k:7} {100 * delta[k] / total:5.1f} %")
print(f"CPU busy: {100 * (total - idle) / total:.1f} %")
ticks in the interval: 485
  user     17.5 %
  system    6.2 %
  idle     75.3 %
  iowait    1.0 %
CPU busy: 23.7 %

/proc/sys: tuning the kernel with sysctl

/proc/sys/ is the writable part: each file is a kernel parameter (a sysctl). Dots in the sysctl name map to slashes in the path, so net.ipv4.ip_forward is /proc/sys/net/ipv4/ip_forward. Reading is allowed for everyone; writing needs root, and inside a container most of /proc/sys is mounted read-only:

bash · try it yourself
cat /proc/sys/kernel/hostname
cat /proc/sys/kernel/pid_max > /dev/null && echo "pid_max is readable"
{ echo 1 > /proc/sys/net/ipv4/ip_forward; } 2>&1 | sed 's/^.*line [0-9]*: //'
tad
pid_max is readable
/proc/sys/net/ipv4/ip_forward: Read-only file system

On a normal machine, an administrator changes these settings like this (sample session):

bash
ada@ubuntu:~$ sysctl vm.swappiness
vm.swappiness = 60
ada@ubuntu:~$ sudo sysctl -w vm.swappiness=10          # now, until reboot
vm.swappiness = 10
ada@ubuntu:~$ echo 'vm.swappiness = 10' | sudo tee /etc/sysctl.d/99-swap.conf   # permanent
vm.swappiness = 10
ada@ubuntu:~$ sudo sysctl --system                     # re-apply all sysctl.d files

Commonly tuned parameters: net.ipv4.ip_forward (route packets: needed for Docker, VPNs, routers), vm.swappiness (how eagerly to swap), fs.inotify.max_user_watches (IDE file watchers running out), kernel.pid_max, net.core.somaxconn (listen backlog) and kernel.dmesg_restrict.

/sys: devices, drivers and modules

/proc grew without a plan; /sys (sysfs, since Linux 2.6) is organised strictly as the kernel's device model: one directory per kernel object, one value per file.

Path Contains
/sys/devices/ The real device tree, by bus: pci0000:00/…/nvme/nvme0
/sys/class/ Devices grouped by kind: net/, block/, tty/, backlight/, power_supply/ (symlinks into devices)
/sys/bus/ Buses (pci, usb, platform) with their devices and drivers
/sys/module/ Loaded modules and their parameters (Kernel Modules & Drivers)
/sys/block/ Block devices and their queue settings
/sys/fs/cgroup/ The cgroup v2 hierarchy (resource limits for services and containers)
/sys/firmware/efi/ Present only if the system booted via UEFI

The sandbox has no network cards, but it does have the loopback interface:

bash · try it yourself
ls /sys/class/net
for f in mtu address operstate; do
  printf '%-10s %s\n' "$f" "$(cat /sys/class/net/lo/$f)"
done
[ -d /sys/firmware/efi ] && echo "booted via UEFI" || echo "no /sys/firmware/efi visible here"
lo
mtu        65536
address    00:00:00:00:00:00
operstate  unknown
no /sys/firmware/efi visible here

On a laptop, the same style of file gives you the battery level and lets you change the screen brightness (sample session):

bash
ada@ubuntu:~$ cat /sys/class/power_supply/BAT0/capacity
83
ada@ubuntu:~$ cat /sys/class/power_supply/BAT0/status
Discharging
ada@ubuntu:~$ cat /sys/class/backlight/intel_backlight/max_brightness
19200
ada@ubuntu:~$ echo 9600 | sudo tee /sys/class/backlight/intel_backlight/brightness
9600
ada@ubuntu:~$ cat /sys/block/nvme0n1/queue/scheduler
[none] mq-deadline kyber bfq

The square brackets mark the active choice, a common sysfs convention.

And on Windows?

Windows has no /proc. The same information comes through APIs and their tools: Performance Counters and WMI/CIM (Get-CimInstance Win32_Process), the registry for configuration (The Windows Registry), and Device Manager / pnputil for devices. The idea of "the kernel publishes live state as a tree" survives in PowerShell's providers, which let you cd into the registry or the certificate store.

Learn more: Processes · Bash: Processes · Kernel Modules & Drivers

Test yourself

What does cat /proc/self/comm print?

  1. bash
  2. cat
  3. self
  4. The PID of the shell

Which file corresponds to the sysctl net.ipv4.ip_forward?

  1. /etc/net/ipv4/ip_forward
  2. /proc/sys/net/ipv4/ip_forward
  3. /sys/class/net/ip_forward
  4. /proc/net/ip_forward

Why does stat report a size of 0 for /proc/meminfo?

  1. The file is empty
  2. Its contents are generated by the kernel only when it is read
  3. Only root can see the size
  4. It is a symlink