Operating Systems Module 7: Storage and files Lesson 7.3 12 min

Files and directories

What a file descriptor really is, why a forked child shares its parent’s position in a file, and how directories, hard links and symbolic links fit together.

You have opened files in every language you have used, and you got something back: a file object in Python, a File in Java, a number in C. Underneath, they all hold the same thing, a small integer the kernel gave you. What is that number, and what happens to it when your program calls fork?

This lesson is about the interface to files that the operating system gives every program, and the three tables inside the kernel that stand behind it.

A file is a stream of bytes

To the kernel, a file is a named, numbered array of bytes that can grow. It does not know whether the bytes are a photo, a text file or a database. That is the program’s business. The kernel’s job is to find the bytes and move them.

Five system calls cover almost everything a program does with a file:

  • open(path, flags) finds the file and returns a file descriptor, a small integer;
  • read(fd, buf, n) copies up to n bytes from the file into your buffer, starting at the current position, and moves the position forward;
  • write(fd, buf, n) does the same in the other direction;
  • lseek(fd, offset, whence) moves the position without reading or writing;
  • close(fd) gives the descriptor back.

The word that matters is position. Every open file has a current offset, and read and write use it and move it. That is why two reads in a row return consecutive pieces of the file instead of the same bytes twice.

File descriptors

A file descriptor is a number that stands for “an open file, as far as this process is concerned”. Every process starts with three already open, inherited from whoever started it:

number name usually
0 standard input the keyboard
1 standard output the screen
2 standard error the screen

That is why printf writes to the screen without you opening anything: it writes to descriptor 1 (Lesson 1.3). When you open a file, the kernel gives you the lowest number not in use, so the first file a program opens normally gets descriptor 3.

This program shows all five calls working on a temporary file under /tmp. mkstemp makes a file with a unique name and opens it in one step. It writes 12 bytes, moves the position back, reads a piece, and removes the file.

files.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(void) {
    char path[] = "/tmp/stc_demo_XXXXXX";      /* the X's are replaced to make the name unique */
    int fd = mkstemp(path);                    /* create the file and open it: returns a descriptor */
    if (fd < 0) { perror("mkstemp"); return 1; }
    printf("descriptor: %d\n", fd);

    const char *text = "hello, files";
    ssize_t w = write(fd, text, strlen(text)); /* the position moves forward by the bytes written */
    printf("wrote %zd bytes, offset now %ld\n", w, (long)lseek(fd, 0, SEEK_CUR));

    lseek(fd, 7, SEEK_SET);                    /* move the position to byte 7: no data is read or written */
    char buf[16];
    ssize_t r = read(fd, buf, sizeof buf - 1); /* read from the new position */
    if (r < 0) { perror("read"); return 1; }
    buf[r] = '\0';                             /* make it a C string */
    printf("read %zd bytes from offset 7: %s\n", r, buf);

    close(fd);                                 /* give the descriptor back */
    unlink(path);                              /* remove the name (and, with no names left, the file) */
    printf("file still there: %s\n", access(path, F_OK) == 0 ? "yes" : "no");
    return 0;
}

Output (one run)

descriptor: 3
wrote 12 bytes, offset now 12
read 5 bytes from offset 7: files
file still there: no

The descriptor is 3, as promised. After writing 12 bytes the position is 12, which is why the program has to lseek back before reading: reading from position 12 would find nothing. And lseek only changed the position. The read after it returned the 5 bytes from byte 7 onwards.

Three tables inside the kernel

A descriptor is only a number. Behind it are three tables, and the difference between them explains how fork behaves.

  1. The descriptor table belongs to one process. Slot 3 holds a pointer to an entry in the next table.
  2. The open file table is system-wide. Each entry is one opening of a file: it holds the current position (and the mode, read or write) and points to the file’s inode.
  3. The inode table has one entry per file. The inode describes the file itself: its size, its owner, where its data blocks are (Lesson 7.4). It knows nothing about positions.

Watch the tables fill in the simulator. The tree on the top shows the directories and files, with their inode numbers. Under it, the process’s descriptor table points to entries in the open file table.

open, read and lseek: the position lives in the open file entry

  1. open /home/ana/notes.txt: descriptor 3 The kernel looks the path up (7 block reads, as in a lookup), makes a new entry in the system-wide open file table, with the position at 0, and puts its address in the lowest free slot of the process's descriptor table. That slot number, 3, is what open returns. Descriptors 0, 1 and 2 are already taken by standard input, output and error.
    Operation
    open /home/ana/notes.txt
    Returned
    fd 3
    Block reads
    7
  2. read 100 bytes from fd 3 The descriptor leads to open file entry 1, whose position is 0. The kernel reads 100 bytes (1 block read) and moves the position to 100.
    Operation
    read 3 100
    Returned
    100 bytes
    Position
    100
    Block reads
    1
  3. lseek(3, 0) lseek changes only the position stored in the open file entry. It reads nothing and writes nothing: the next read or write simply starts there.
    Operation
    lseek 3 0
    Position
    0
  4. read 50 bytes from fd 3 The descriptor leads to open file entry 1, whose position is 0. The kernel reads 50 bytes (1 block read) and moves the position to 50.
    Operation
    read 3 50
    Returned
    50 bytes
    Position
    50
    Block reads
    1
  5. close(3) The slot in the descriptor table is freed, and so is the open file entry: nothing points to it any more.
    Operation
    close 3

Notice what open did: it walked the path (the block reads you can see in the Blocks view are the subject of Lesson 7.4), made a new entry in the open file table, put its address into the lowest free slot of the descriptor table, and returned that slot’s number. After close, the slot is free and the entry is gone.

Why a forked child shares the position

Now the part that surprises people. When a process forks (Lesson 2.3), the child gets a copy of the descriptor table. The copy holds the same numbers, and each number points at the same entry in the open file table. The entries are not copied.

After fork, parent and child share the position

  1. open /home/ana/notes.txt: descriptor 3 The kernel looks the path up (7 block reads, as in a lookup), makes a new entry in the system-wide open file table, with the position at 0, and puts its address in the lowest free slot of the process's descriptor table. That slot number, 3, is what open returns. Descriptors 0, 1 and 2 are already taken by standard input, output and error.
    Operation
    open /home/ana/notes.txt
    Returned
    fd 3
    Block reads
    7
  2. read 100 bytes from fd 3 The descriptor leads to open file entry 1, whose position is 0. The kernel reads 100 bytes (1 block read) and moves the position to 100.
    Operation
    read 3 100
    Returned
    100 bytes
    Position
    100
    Block reads
    1
  3. fork copies the descriptor table fork gives the child a copy of the parent's file descriptor table. The copy holds the same numbers, and each number points at the same entry in the system-wide open file table. The entries are not copied. So the parent and the child share each open file, including its current position.
    Operation
    fork
    Parent fds
    0, 1, 2, 3
    Child fds
    0, 1, 2, 3
  4. The child reads 50 bytes from fd 3 The descriptor leads to open file entry 1, whose position is 100. The kernel reads 50 bytes (1 block read) and moves the position to 150. The entry is shared by 2 descriptors, so the other process sees the new position too.
    Operation
    child: read 3 50
    Returned
    50 bytes
    Position
    150
    Block reads
    1
  5. read 50 bytes from fd 3 The descriptor leads to open file entry 1, whose position is 150. The kernel reads 50 bytes (1 block read) and moves the position to 200. The entry is shared by 2 descriptors, so the other process sees the new position too.
    Operation
    read 3 50
    Returned
    50 bytes
    Position
    200
    Block reads
    1

That is why (echo one; echo two) > out.txt leaves both lines in the file. The shell opens out.txt once, and each echo runs in a forked child that inherits the same open file entry, so the second one writes after the first instead of on top of it. Pipes and redirection both rely on descriptors being inherited this way.

If a process opens the same file twice, though, it gets two separate entries and two independent positions:

Opening a file twice gives two independent positions

  1. open /home/ana/notes.txt: descriptor 3 The kernel looks the path up (7 block reads, as in a lookup), makes a new entry in the system-wide open file table, with the position at 0, and puts its address in the lowest free slot of the process's descriptor table. That slot number, 3, is what open returns. Descriptors 0, 1 and 2 are already taken by standard input, output and error.
    Operation
    open /home/ana/notes.txt
    Returned
    fd 3
    Block reads
    7
  2. read 100 bytes from fd 3 The descriptor leads to open file entry 1, whose position is 0. The kernel reads 100 bytes (1 block read) and moves the position to 100.
    Operation
    read 3 100
    Returned
    100 bytes
    Position
    100
    Block reads
    1
  3. open /home/ana/notes.txt: descriptor 4 The kernel looks the path up (7 block reads, as in a lookup), makes a new entry in the system-wide open file table, with the position at 0, and puts its address in the lowest free slot of the process's descriptor table. That slot number, 4, is what open returns. Descriptors 0, 1 and 2 are already taken by standard input, output and error.
    Operation
    open /home/ana/notes.txt
    Returned
    fd 4
    Block reads
    7
  4. read 10 bytes from fd 4 The descriptor leads to open file entry 2, whose position is 0. The kernel reads 10 bytes (1 block read) and moves the position to 10.
    Operation
    read 4 10
    Returned
    10 bytes
    Position
    10
    Block reads
    1

Directories and paths

A directory is a file too, one whose contents are a list of names, each paired with an inode number. A file’s name is not part of the file. It lives in the directory that contains it, which is why one file can have several names, and why renaming a file within a directory touches only that directory.

A path is a trip through directories. An absolute path such as /home/ana/notes.txt starts at the root and names every directory on the way. A relative path starts from the process’s current directory. The kernel keeps one for every process, and cd changes it. Two entries exist in every directory: . (the directory itself) and .. (its parent).

Because the name is only an entry in a directory, you can have more than one. A hard link is a second directory entry pointing to the same inode. Both names are equally real. The inode keeps a link count, and the file’s data is freed only when the last name is removed and no process has it open.

A symbolic link (symlink) is different: it is a small file of its own whose content is a path. When the kernel meets it in a lookup, it starts again with that path. That makes symlinks flexible: they can point to directories and across file systems, and they can dangle, pointing to something that has since gone. A hard link cannot dangle, but it cannot cross file systems, because an inode number only means something inside one.

A hard link and a symbolic link to the same file

  1. Read the root inode A path is read from the root. The root directory is always inode 2, so the kernel can start there: it reads the inode from block 2 of the inode table. The inode says where the directory's data lives: block 14.
    Operation
    lookup /home/ana/short
    Block reads
    1 so far
    Disk consistent
    yes
  2. Read the data of / The inode of / says its data is in block 14, so the kernel reads that block. A directory's data is a list of names and inode numbers. The entry it wants gives inode 12.
    Operation
    lookup /home/ana/short
    Block reads
    2 so far
    Disk consistent
    yes
  3. Read inode 12 (home) The directory entry gave the inode number 12. The kernel reads that inode from block 2 of the inode table. It is a directory, with its data in block 16.
    Operation
    lookup /home/ana/short
    Block reads
    3 so far
    Disk consistent
    yes
  4. Read the data of /home The inode of /home says its data is in block 16, so the kernel reads that block. A directory's data is a list of names and inode numbers. The entry it wants gives inode 13.
    Operation
    lookup /home/ana/short
    Block reads
    4 so far
    Disk consistent
    yes
  5. Read inode 13 (ana) The directory entry gave the inode number 13. The kernel reads that inode from block 2 of the inode table. It is a directory, with its data in block 17.
    Operation
    lookup /home/ana/short
    Block reads
    5 so far
    Disk consistent
    yes
  6. Read the data of /home/ana The inode of /home/ana says its data is in block 17, so the kernel reads that block. A directory's data is a list of names and inode numbers. The entry it wants gives inode 15.
    Operation
    lookup /home/ana/short
    Block reads
    6 so far
    Disk consistent
    yes
  7. Read inode 15 (short): a symbolic link This inode is a symbolic link. Its content is a path, /home/ana/notes.txt, stored right in the inode. The kernel starts the lookup again from the root, using that path.
    Operation
    lookup /home/ana/short
    Block reads
    7 so far
    Disk consistent
    yes
  8. Read inode 2 (/) The directory entry gave the inode number 2. The kernel reads that inode from block 2 of the inode table. It is a directory, with its data in block 14.
    Operation
    lookup /home/ana/short
    Block reads
    8 so far
    Disk consistent
    yes
  9. Read the data of / The inode of / says its data is in block 14, so the kernel reads that block. A directory's data is a list of names and inode numbers. The entry it wants gives inode 12.
    Operation
    lookup /home/ana/short
    Block reads
    9 so far
    Disk consistent
    yes
  10. Read inode 12 (home) The directory entry gave the inode number 12. The kernel reads that inode from block 2 of the inode table. It is a directory, with its data in block 16.
    Operation
    lookup /home/ana/short
    Block reads
    10 so far
    Disk consistent
    yes
  11. Read the data of /home The inode of /home says its data is in block 16, so the kernel reads that block. A directory's data is a list of names and inode numbers. The entry it wants gives inode 13.
    Operation
    lookup /home/ana/short
    Block reads
    11 so far
    Disk consistent
    yes
  12. Read inode 13 (ana) The directory entry gave the inode number 13. The kernel reads that inode from block 2 of the inode table. It is a directory, with its data in block 17.
    Operation
    lookup /home/ana/short
    Block reads
    12 so far
    Disk consistent
    yes
  13. Read the data of /home/ana The inode of /home/ana says its data is in block 17, so the kernel reads that block. A directory's data is a list of names and inode numbers. The entry it wants gives inode 14.
    Operation
    lookup /home/ana/short
    Block reads
    13 so far
    Disk consistent
    yes
  14. Read inode 14 (notes.txt) The directory entry gave the inode number 14. The kernel reads that inode from block 2 of the inode table. It is a file of 6K (2 blocks). The lookup is done: the name never needed to be stored in the inode.
    Operation
    lookup /home/ana/short
    Block reads
    14 so far
    Disk consistent
    yes
  15. Found /home/ana/short: inode 14 The lookup took 14 block reads: one inode read for the root, then a directory read and an inode read for every name in the path. Real kernels keep recent lookups in memory (the dentry and inode caches), so most lookups cost no disk reads at all.
    Operation
    lookup /home/ana/short
    Block reads
    14
    Inode number
    14
    Disk consistent
    yes

The hard link copy has the same inode number as notes.txt, and the link count of that inode is 2. The symlink short has an inode of its own. Looking it up cost 14 block reads: one walk of the path to the link, and a second walk for the path it contains.

Now remove the original name and see which kind of link survives:

Delete the name notes.txt: the hard link keeps the file alive

  1. Find where the name goes The kernel reads the directory /home/ana (6 block reads) to find the inode and check the name. Then it works out every block it must write.
    Operation
    delete /home/ana/notes.txt
    Block reads
    6
    Disk consistent
    yes
  2. Plan: 2 block writes One delete is not one write. It is 2 separate block writes, done in this order: the directory block: remove the entry "notes.txt"; inode 14: one link fewer (now 1). The disk can lose power between any two of them. With no journal, the disk holds a half-done change at every point in between.
    Operation
    delete /home/ana/notes.txt
    Block writes
    0 of 2
    Journal
    off
    Disk consistent
    yes
  3. Write 1 of 2: directory block Write the directory block: remove the entry "notes.txt". Right now the disk is inconsistent: inode 14 says it has 2 links, but 1 name points to it.
    Operation
    delete /home/ana/notes.txt
    Block writes
    1 of 2
    Journal
    off
    Disk consistent
    no (1 problem)
  4. Write 2 of 2: inode Write inode 14: one link fewer (now 1).
    Operation
    delete /home/ana/notes.txt
    Block writes
    2 of 2
    Journal
    off
    Disk consistent
    yes
  5. Done: delete /home/ana/notes.txt All 2 block writes finished.
    Operation
    delete /home/ana/notes.txt
    Block writes
    2 of 2
    Disk consistent
    yes

Deleting notes.txt removed a directory entry and lowered the link count from 2 to 1. The data blocks stayed, because a name still pointed to them, and it took only 2 block writes: the directory, and the inode with its new link count. The bitmap was not touched. A symlink to notes.txt would not have helped: it would now point to a path that no longer exists.

This is also why rm is really called unlink in the kernel (unlink is the system call): it removes a name, and the file goes away only when the last name does.

In the real world

Your shell shows all of this. These commands list a process’s open descriptors, show inode numbers, and make both kinds of link:

Terminal
$ ls -l /proc/self/fd
$ ls -li notes.txt
$ ln notes.txt copy
$ ln -s notes.txt short

On Linux, /proc/self/fd has one entry for each descriptor the process has open, and each is a symlink to what it points to, so you can see 0, 1 and 2 pointing at your terminal. ls -li puts the inode number in the first column, so after ln the two hard-linked names show the same number and the same link count, while the symlink shows a different number. Windows has descriptors too, called handles, and NTFS supports hard links and symbolic links, although they are used less often than on Unix. :::

Quick check

Quick check

  1. What is a file descriptor?
  2. A parent opens a file and forks. The child reads 50 bytes. What does the parent see when it reads next?
  3. What is the difference between a hard link and a symbolic link?
  4. What does lseek change?

Your progress is saved in this browser. Sign in to keep it on every device. Free, no password.

Join the discussion