|
|
UNIX System V File and Device I/O functions denote a file by a small positive integer called a ``file-descriptor'' and declared as follows:
int fildeswhere fildes represents the file-descriptor, and the file-descriptor denotes an open file from which data is read or onto which data is written. UNIX System V maintains all information about an open file; the user program refers to the file only by the file-descriptor. Any I/O on the file uses the file-descriptor instead of the filename to denote the file.
Multiple file-descriptors may denote the same file, and each file-descriptor has associated with it information used to do I/O on the file:
Doing I/O on the user's terminal occurs commonly enough that special arrangements make this convenient. When the command interpreter (the ``shell'') runs a program, it opens three files, called the standard input, the standard output and the standard error output, with file-descriptors 0, 1 and 2. All of these are normally connected to the terminal; thus, a program reading file-descriptor 0 and writing file-descriptors 1 and 2, can do terminal I/O without opening the files. If I/O is redirected to and from files with < and >, as in:
prog <infile >outfile
the shell changes the default assignments for file-descriptors 0 and 1 from the terminal to the named files. Similar conventions hold for I/O on a pipe. Normally file-descriptor 2 remains attached to the terminal, so error messages can go there. In all cases, the shell changes the file assignments, the program does not. The program can ignore where its output goes, as long as it uses file-descriptor 0 for input and 1 and 2 for output.