Files and directories
A file is a numbered row of bytes. Our file holds 10: milk, a newline, eggs, a newline. The disk knows it by a number, inode 42, not by its name. An inode is the record that says where the bytes are.
A directory is a file too, but its bytes are a list of pairs: a name and an inode number. Directories hold directories, so they form a tree that starts at the root, written /, which is inode 2 on ext4.
Opening a file
Line 1 asks the kernel, through a system call, to open /home/ada/todo for reading. The path starts with /, so the kernel starts at the root directory, inode 2, and looks up the first name, home. It is inode 7.
The kernel repeats the same move: read directory 7, find ada, inode 19; read directory 19, find todo, inode 42. One lookup per directory. A missing name stops the walk with the error ENOENT.
Inode 42 says Ada may read it, so the kernel makes an open file record: which file (inode 42), how it was opened (read only) and the offset, the place the next read starts. The offset begins at 0.
Each process has its own descriptor table. Slots 0, 1 and 2 are already open: standard input, output and error. The kernel takes the lowest free slot, 3, points it at the open file record, and open() returns 3.
Reading and closing
read(3, buf, 5) follows slot 3 to the open file record. The offset is 0, so the kernel copies bytes 0 to 4, milk and a newline, into buf, adds 5 to the offset and returns 5.
Line 4 is the very same call, but the offset is now 5, so it gets bytes 5 to 9: eggs and a newline. The offset moves to 10, the end. A third read would return 0, which means end of file.
close(3) empties slot 3, so a later open() can reuse the number. No other descriptor points at the open file record, so the kernel frees it too. The file and its directories on the disk are unchanged.
Names live in directories, bytes in the file, and the offset in the open file record. So two open() calls on one file get separate offsets, while fork() and dup() share one record and its offset.
What happens
;; step 1/10 · file
byte 0 1 2 3 4 5 6 7 8 9
value m i l k \n e g g s \n (10 bytes)
low-level name inode 42
the inode size, owner, permissions,
where the bytes sit on the disk
(the next lesson opens it up)
Inode 2 is the root directory on ext2, ext3 and ext4. The other inode numbers (7, 19, 42 and so on) are made up for the example; on a real disk, ls -i shows them. The ↵ mark stands for the newline byte (10 in ASCII) that ends each line of the file. Linux calls the open file record an open file description; textbooks call the table of them the open file table. The descriptor table is private to each process, while the open file records live in one table for the whole system.