CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 4 of 6 · 2 min read

Linux states

Linux uses letters for the states. These are the common ones:

Letter Meaning Matches
R Running or ready to run Running and Ready
S Sleeping, can be woken by a signal Waiting
D Sleeping and cannot be interrupted, usually during disk I/O Waiting
T Stopped, by a signal such as Ctrl+Z A stopped state
Z Zombie: finished but not yet collected (page 8) Terminated

In plain words: Linux does not tell "running" from "ready": both show as R. The S and D states differ in what can wake them. A sleep in D ignores signals until the device answers, which is why a process stuck in D cannot be killed until its I/O completes.

The test machine confirms this. A sleep 30 was started in the background and looked at with ps:

  PID STAT WCHAN                COMMAND
  220 S    hrtimer_nanosleep    sleep

State S, and the column WCHAN says where in the kernel it sleeps, a timer. Sending it the stop signal with kill -STOP 220 changed the line State: in /proc/220/status to T (stopped). A program that reads its own state can only ever find itself running:

#include <stdio.h>
#include <string.h>
static void state(const char *when) {
    FILE *f = fopen("/proc/self/status", "r");
    char line[128];
    while (fgets(line, sizeof line, f))
        if (!strncmp(line, "State:", 6)) printf("%-14s %s", when, line);
    fclose(f);
}
int main(void) {
    state("while running");
    volatile double x = 0;
    for (long i = 0; i < 200000000; i++) x += i;
    state("after loop");
    return 0;
}
while running  State:   R (running)
after loop     State:   R (running)

The program can never print S, because to read the line it must be running. Only another process can see it sleeping.

Read it as

R means "wants the processor", S and D mean "waiting for something", T means "stopped on purpose" and Z means "dead, not yet collected".

Check yourself: 1. Which letter shows a process stuck in disk I/O? 2. Why does a program never see itself in state S? 3. What does T mean?