File descriptor

From LQWiki
Jump to navigation Jump to search

A file descriptor is an abstraction of a file being read from/written to by a process. It is created and exposed by the.kernel purely for the convenience of the user, where the convenience is typically realized in its shorter length canonical path and/or the ability to script interactions even when its path is not supplied as an input.

Every process keeps a list of file descriptors, virtual files representing the open files the process is accessing. Note that many processes can make use of the same file descriptor. The kernel keeps track of the file descriptors.

Examination per process

You can take a peek at the file descriptors a process has open. First, get a process number with ps.

$ ps
  PID TTY          TIME CMD
  …
14649 pts/8    00:00:00 bash
14675 pts/8    00:00:00 ps
  …

Then, you look through a special directory, /proc, which keeps runtime information about processes. (It's not a directory representing your hard drive; Rather, it is a virtual directory representing kernel information.)

$ ls -l /proc/14649/fd
total 0
lrwx------    1 lion     lion           64 Aug 16 07:32 0 -> /dev/pts/8
lrwx------    1 lion     lion           64 Aug 16 07:32 1 -> /dev/pts/8
lrwx------    1 lion     lion           64 Aug 16 07:32 2 -> /dev/pts/8

Why did we look at directory /proc/14649/fd?

  • /proc is for "process information"
  • /14649 is for "process #14649", the running bash shell
  • /fd is for "file descriptors", the list of the process' open file descriptors

Now we see that we have three open file descriptors: 0, 1 and 2.

Opening and closing file descriptors

There are several ways to manually open and close file descriptors.

  • In C, you can use the fcntl library to open and close file descriptors.

Bash shell

This explanation here goes by way of Bash scripting. To open a file descriptor, you write:

$ exec 3<> File

To close the same file descriptor, you write:

$ exec 3>&-

The 3 means "file descriptor #3". The word File is the name of a file in the working directory.

Forked processes

When a process is forked, the forked process shares all file descriptors with its parent.

Sources