When a process duplicates itself, the kernel makes a copy of all open file descriptors. A file descriptor is an integer that refers to an open file or device, and it is used for reading and writing. If a program has a file open before the
fork, what happens if both processes try a read or a write? Will one process overwrite data from the other? Will two copies of the file be read? Listing 5 investigates this by opening up two files — one for reading and one for writing — and having both the parent and the child read and write simultaneously.
Listing 5 is a simple program that opens a file and
forks into the parent and child. Each process reads from the same file descriptor (which is just a text file with the numbers 1 through 7), printing what was read along with the PID. After reading a line, the PID is written to the out file. The loop completes when there are no more characters to read in the in file.
The output of Listing 5 shows that as one process reads from the file, and the file pointer is moved for both processes. Likewise, when a file is written to, the next character goes to the end of the file. This makes sense, because the kernel keeps track of the open file’s information. The file descriptor is merely an identifier for the process.
You might also know that the standard output (the screen) is a file descriptor, too. This is duplicated during the
fork, which is why both processes can write to the screen.