Shared File Table Entries: fork() and dup()

This lesson discusses a few ways when an instance of an opened file can be shared between multiple programs.

We'll cover the following

In many cases (as in the examples shown in the previous lesson), the mapping of file descriptor to an entry in the open file table is a one-to-one mapping. For example, when a process runs, it might decide to open a file, read it, and then close it; in this example, the file will have a unique entry in the open file table. Even if some other process reads the same file at the same time, each will have its own entry in the open file table. In this way, each logical reading or writing of a file is independent, and each has its own current offset while it accesses the given file.

However, there are a few interesting cases where an entry in the open file table is shared.

fork()

One of those cases occurs when a parent process creates a child process with fork(). Shown below is a small code snippet in which a parent creates a child and then waits for it to complete. The child adjusts the current offset via a call to lseek() and then exits. Finally, after waiting for the child, the parent checks the current offset, and prints out its value.

Get hands-on with 1200+ tech skills courses.