Part 6 of 8 · 3 min read
Seeing them
Think of the meter readings of a household. The numbers do not explain the day, but they show which appliance ran and for how long. The file /proc/interrupts is that meter for interrupts. The analogy stops in one place: a meter counts power, and this file counts events for each processor.
In plain words: Linux shows interrupt counts in the file /proc/interrupts. Each row is an interrupt source and each column a processor. On the test machine, the first lines were:
CPU0 CPU1
24: 1 0 IO-APIC 5-edge ACPI:Ged
26: 5 0 IO-APIC 4-edge ttyS0
28: 0 0 PCI-MSIX 0-edge virtio0-config
Read it as follows. Number 26 is the serial console. Processor 0 has handled 5 of its interrupts and processor 1 none. Run cat /proc/interrupts twice, with a keystroke or a network transfer in between, and the counts for the matching device grow.
The key lines.
Next, a program that behaves like a tiny interrupt-driven system. The timer here is a software one, using the signal the OS sends when a timer expires. The main loop only counts. The handler, which runs without the main loop calling it, counts the ticks:
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <sys/time.h>
static volatile sig_atomic_t ticks = 0;
static void on_tick(int sig) { /* plays the part of an interrupt handler */
(void)sig;
ticks++;
}
int main(void) {
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = on_tick;
sigaction(SIGALRM, &sa, NULL);
struct itimerval t = { {0, 100000}, {0, 100000} }; /* every 100 ms */
setitimer(ITIMER_REAL, &t, NULL);
unsigned long long work = 0;
while (ticks < 10)
work++;
printf("ticks=%d, main loop never called the handler\n", (int)ticks);
return work > 0 ? 0 : 1;
}
Output, and the run took 1.0 second:
ticks=10, main loop never called the handler
Ten ticks of 100 milliseconds make 1 second, and the program stopped when the tenth tick arrived. The loop never called on_tick. The kernel interrupted the loop, ran the handler, and resumed the loop where it left off, just as the hardware does for a device. The variable is marked volatile because the handler changes it while the loop reads it, and the compiler must not assume it stays constant.
The real timer interrupt works at a finer scale. With the Linux setting HZ = 250 there are 250 timer interrupts a second, one every 4 milliseconds. That is also how the kernel takes the processor back from a program that never gives it up (page 2).
Read it as
An interrupt makes a program's flow jump to a handler and then jump back. The program does not know it happened. The only visible effect is that time passes.
Check yourself:
1. What does a row of /proc/interrupts show?
2. Why was ticks declared volatile?
3. How many timer interrupts occur in 10 seconds at HZ = 250?