This chapter covers the basics of reading to and writing from files. Such operations form the core of a Unix system. The next chapter covers standard I/O from the standard C library, and Chapter 4 continues the coverage with a treatment of the more advanced and specialized file I/O interfaces. Chapter 7 rounds out the discussion by addressing the topic of file and directory manipulation.
Before a file can be read from or written to, it must be opened. The kernel maintains a per-process list of open files, called the file table. This table is indexed via nonnegative integers known as file descriptors (often abbreviated fds). Each entry in the list contains information about an open file, including a pointer to an in-memory copy of the file’s backing inode and associated metadata, such as the file position and access modes. Both user space and kernel space use file descriptors as unique per-process cookies. Opening a file returns a file descriptor, while subsequent operations (reading, writing, and so on) take the file descriptor as their primary argument.
By default, a child process receives a copy of its parent’s file table. The list of open files and their access modes, current file positions, and so on, are the same, but a change in one process—say, the child closing a file—does not affect the other process’ file table. However, as you’ll see in Chapter 5, it is possible for the child and parent to share the parent’s file table (as threads do).
File descriptors ...