Chapter 4: File I/O: The Universal I/O Model

With this chapter, we start to look in earnest at the system call API. We start with files, since they are central to the Unix philosophy. The focus of this chapter is the system calls used for performing file input and output.

We begin by introducing the concept of a file descriptor, and then look at the system calls that constitute the so-called universal I/O model. These are the system calls that open and close a file, and read and write data. In addition, we look at the system call that is used to seek to a random location in a file.

We focus on I/O on disk files. However, much of the material covered here is relevant for later chapters, since the same system calls are used for performing I/O on all types of files, such as pipes and terminals.

We continue the discussion of file I/O with further details in Chapter 5. One other aspect of file I/O, buffering, is complex enough to deserve its own chapter. In Chapter 13, we cover I/O buffering in the kernel and in the stdio library.

4 File I/O: The Universal I/O Model
4.1 Overview
4.2 Universality of I/O
4.3 Opening a File: open()
4.4 Reading from a File: read()
4.5 Writing to a File: write()
4.6 Closing a File: close()
4.7 Changing the Current File Offset: lseek()
4.8 Operations Outside the Universal I/O Model: ioctl()
4.9 Summary
4.10 Exercises


  1. With recent Linux kernel changes like rename and fsync behavior on ext4, RELATIME becoming the default for ext3, and the Emacs compile mode losing data from PTY problem in 2.6.31, I think many userspace developers are really looking for guidance on how to use system I/O functions correctly and efficiently.

    Do you plan to cover topics such as how RELATIME trades POSIX conformance for efficiency?

  2. @Scott Tsai: Yes, MS_RELATIME, MS_STRICTATIME, MS_NOATIME, NO_DIRATIME all get discussed (Ch. 14), as does open() O_NOATIME (Section 4.3). Also the related FS_NOATIME_FL flag (one of the so-called i-node flags, also sometimes known as ext2 extended file attributes) is described in Section 15.5.