ENع
←Files and descriptors
Lesson 40 · File systems

Files, directories and file descriptors

14 min10 steps5 questionsAdvanced
About this lesson

You type a path like /home/ada/todo, and a program gets back a small number, 3, that it uses to read the file. What happened in between? Follow one open() as the kernel walks the path one directory at a time, builds an open file record with an offset, and hands back a file descriptor. Then watch two identical read() calls return different bytes, because the offset moved. The Linux lessons The file system and Disks, partitions and mounts show the same files from the user's side; here we look at what the kernel keeps for them. System calls: crossing into the kernel shows how open() and read() enter the kernel.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 40 · Interactive
01 / 10

A file is just bytes

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.

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)
Loading figure…
or ← →
Read the lesson step by step
  1. A file is just bytes

    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.

    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)
  2. A directory is a list

    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.

    directory   entries (name -> inode number)
    / (2)       etc -> 3   home -> 7
    home (7)    ada -> 19   bob -> 20
    ada (19)    notes -> 31   todo -> 42
    
    every directory also holds  .  (itself)  and  ..  (its parent)
    the name lives in the directory, not in the file
  3. open() starts at the root

    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.

    path      /home/ada/todo
    names     home   ada   todo
    
    start     /  (inode 2, the root directory)
    look up   home  ->  inode 7
    check     may this process search / ?  yes
  4. One name at a time

    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.

    directory 7    ada   ->  inode 19
    directory 19   todo  ->  inode 42
    
    walk  2 -> 7 -> 19 -> 42
    
    missing name             ENOENT (no such file)
    no search permission     EACCES
  5. The kernel opens the file

    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.

    open file record  (Linux: an open file description)
      inode    42
      mode     read only   (O_RDONLY)
      offset   0
    
    it lives in kernel memory, in a table shared by all processes
  6. The file descriptor is 3

    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.

    this process's descriptor table
      fd 0   standard input    (the terminal)
      fd 1   standard output   (the terminal)
      fd 2   standard error    (the terminal)
      fd 3   -> open file record (inode 42, offset 0)
    
    open("/home/ada/todo", O_RDONLY) returns 3
    fd is just an index: only the kernel can follow it
  7. read() follows the chain

    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.

    read(3, buf, 5)
      fd 3  ->  open file record  ->  inode 42  ->  bytes
      offset 0: copy bytes 0..4    "milk\n"
      offset 0 -> 5
      returns 5   (bytes read)
  8. Same call, next bytes

    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.

    read(3, buf, 5)
      offset 5: copy bytes 5..9    "eggs\n"
      offset 5 -> 10   (the file has 10 bytes)
      returns 5
    
    read(3, buf, 5) again   returns 0   = end of file
  9. close() frees the slot

    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.

    close(3)
      fd 3              free (the next open may return 3 again)
      open file record  freed: no descriptor refers to it
      inode 42, bytes   unchanged on disk
      returns 0
  10. Why three layers?

    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.

    the same machinery as a Python simulation:
    
    disk = {                          # inode number -> contents
        2:  {"etc": 3, "home": 7},     # the root directory
        7:  {"ada": 19, "bob": 20},
        19: {"notes": 31, "todo": 42},
        42: b"milk\neggs\n",          # a plain file: 10 bytes
    }
    fds = ["tty", "tty", "tty"]       # this process: 0, 1, 2 open
    
    def open_(path):
        ino = 2                       # start at the root
        for name in path.strip("/").split("/"):
            ino = disk[ino][name]     # one lookup per directory
        entry = {"inode": ino, "offset": 0}   # the open file
        fd = fds.index(None) if None in fds else len(fds)
        fds[fd:fd + 1] = [entry]      # lowest free slot
        return fd
    
    def read(fd, n):
        f = fds[fd]
        data = disk[f["inode"]][f["offset"]:f["offset"] + n]
        f["offset"] += len(data)      # the offset moves on
        return data
    
    fd = open_("/home/ada/todo")
    print(fd, read(fd, 5), read(fd, 5), read(fd, 5))
    
    prints:
    3 b'milk\n' b'eggs\n' b''

Quiz Unlocks after the last step.