Tracking Open File Objects
In this lesson, you will learn how the Linux kernel keeps track of open files so that multiple processes can reliably read from or write to the same data stream.
Understanding the "Open File Description"
When a process calls open(), the kernel creates a File Descriptor (FD) in that process's private table. However, the kernel also creates a deeper, system-wide entity called an Open File Description. Think of this as the "object" that holds the actual state of the open file: specifically, the current file offset (the "cursor" position) and the access mode (read/write).
Normally, each open() call creates a new, independent File Description. But what happens when processes share one?
Sharing and Inheritance
There are two primary ways processes end up sharing the same underlying file object:
- Forking: When a process calls
fork(), the child process receives a duplicate of the parent's file descriptor table. Because the child points to the exact same "Open File Description" as the parent, they share the file offset. If the parent reads 10 bytes, the child’s "cursor" moves forward by 10 bytes as well. dup()system calls: Usingdup()ordup2()allows a process to create a second file descriptor that points to the same file object as an existing descriptor.
Consider this logical flow:
// Process A opens a file
int fd1 = open("log.txt", O_RDWR);
// Process A forks; both processes now share the file object
if (fork() == 0) {
// Child process reads 5 bytes
read(fd1, buffer, 5);
} else {
// Parent waits, then reads
wait(NULL);
// The parent's cursor is already at position 5
read(fd1, buffer, 5);
}
Because both processes point to the same "Open File Description," they effectively coordinate their position within the file. If you were to open the file twice using two separate open() calls, you would have two separate offsets, and the processes would overwrite each other’s progress. By sharing the file object, the kernel ensures that "sequential" reading remains consistent across process boundaries.
Key Takeaway: The kernel tracks file state in a system-wide "Open File Description," meaning processes sharing the same description automatically share the same file cursor position.