File Descriptors#

A file descriptor (fd) represents an entry in the operation system’s global open file table. Whenever a process requests to open a file, the kernel creates an entry in the open file table and returns a file descriptor to that process. Every process has its own table of file descriptors.

Multiple file descriptors can reference to same entry in the kernel file table. It does not matter which file descriptor is used. All meta-data is stored in the file table, such that, for example, seeking in that file changes the file position for all file descriptors.

Representation of File Descriptors#

File descriptors are numbered, starting from 0. All processes have their own descriptors. They are exposed in /proc/$pid/fd and /proc/$pid/fdinfo. A file in proc/$pid/fd is a symbolic links and the target is the name of the corresponding file, device or internal object associated to that file descriptor.

Every process can access their file descriptors via /proc/self/fd.

Standard File Descriptors#

Each process has at least 3 file descriptors. They have the numbers 0, 1 and 2 and are called the standard file descriptors:

fd

Name

Usage

0

stdin

Standard input

1

stdout

Standard output

2

stderr

Standard error, output of errors or additional information

In case of terminal window, they are usually attached to a (pseudo) terminal device in /dev/pts/. The descriptor stdin is used for reading from the character device (e.g. keyboard input), while stdout and stderr usually point to the same file entry which is opened for writing to the character device (e.g terminal output).

Note

Example: A terminal with bash (pid 17757) has four file descriptors. The three standard file descriptors are all pointing to the pseudo terminal device /dev/pts/1. FD 255 is bash specific. In fact file descriptors 1 and 2, (respectively 0 and 255) reference to same entry in the open file table. More information is shown by lsof.

$ ls -log /proc/17757/fd
lrwx------ 1 64 Oct 11 17:38 0 -> /dev/pts/1
lrwx------ 1 64 Oct 11 17:38 1 -> /dev/pts/1
lrwx------ 1 64 Oct 11 17:38 2 -> /dev/pts/1
lrwx------ 1 64 Oct 11 17:38 255 -> /dev/pts/1