Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

3


File I/O


3.1 Introduction


We’ll start our discussion of the UNIX System by describing the functions available for
file I/O—open a file, read a file, write a file, and so on. Most file I/O on a UNIX system
can be performed using only five functions:open,read,write,lseek,andclose.
We then examine the effect of various buffer sizes on thereadandwritefunctions.
The functions described in this chapter areoften referred to asunbuffered I/O,in
contrast to the standardI/O routines, which we describe in Chapter 5. The term
unbufferedmeans that eachreadorwriteinvokes a system call in the kernel. These
unbuffered I/O functions arenot part of ISO C, but arepart of POSIX.1 and the Single
UNIX Specification.
Whenever we describe the sharing of resources among multiple processes, the
concept of an atomic operation becomes important. We examine this concept with
regard to file I/O and the arguments to theopenfunction. This leads to a discussion of
how files areshared among multiple processes and which kernel data structures are
involved. After describing these features, we describe thedup,fcntl,sync,fsync,
andioctlfunctions.

3.2 File Descr iptors


To the kernel, all open files arereferred to by file descriptors. Afile descriptor is a
non-negative integer.When we open an existing file or create a new file, the kernel
returns a file descriptor to the process. When we want to read or write a file, we
identify the file with the file descriptor that was returned byopenorcreatas an
argument to eitherreadorwrite.

61
Free download pdf