0read1write2openKERNELfd 0infd 1outfd 2err$ ./proghiwrite: Bad filedescriptorKERNEL ONLYKERNEL ONLY1n = write(1, "hi\n", 3);2m = write(9, "hi\n", 3);3if (m < 0) perror("write");raxrdirsirdxmodeusernmerrnolibc: write()11hi39-9
Back: the kernel's side (syscall table, kernel, open files, screen)Front: the user's side (your program, the C library, the registers, its memory)Tokens: the request, the call number, the file descriptor and the answerThe kernel's side at the back: the system call table, the kernel, this program's open files and the screen. A wall marked kernel only, with one gate. The user's side in front: the program, the C library, the CPU registers and the program's memory. Line 1's write goes through libc into the registers, through the gate, through the table to sys_write, which checks fd 1 and prints hi; 3 comes back. Line 2 uses fd 9, which is not open: -9 comes back and libc turns it into m = -1 and errno = 9. The call number 1 for write, the registers rax, rdi, rsi and rdx, and the instructions syscall and sysret are for Linux on x86-64. Other systems use other numbers: on 64-bit ARM Linux write is 64, and xv6 on RISC-V puts the number in a7 and traps with ecall. The idea is the same everywhere.

Making the request

  1. A program cannot run kernel code itself. Instead it makes a system call: a request that names a service by number, carries a few arguments, and enters the kernel through the system call entry point. The kernel does the work and sends back an answer.

Inside the kernel

When it fails

What happens

;; step 1/12 · ask
the whole program (C99, POSIX):

#include <stdio.h>
#include <unistd.h>

int main(void) {
    ssize_t n, m;
    n = write(1, "hi\n", 3);
    m = write(9, "hi\n", 3);
    if (m < 0) perror("write");
    return n == 3 ? 0 : 1;
}

line 1   a write that works
line 2   the same write to a file descriptor that is not open
line 3   report the error

The call number 1 for write, the registers rax, rdi, rsi and rdx, and the instructions syscall and sysret are for Linux on x86-64. Other systems use other numbers: on 64-bit ARM Linux write is 64, and xv6 on RISC-V puts the number in a7 and traps with ecall. The idea is the same everywhere. The table shows only the first three entries. Recent Linux kernels on x86-64 compile the table into a switch statement rather than looking it up in an array, but it does the same job: number in, handler out.