File descriptor

From LQWiki
Jump to: navigation, search

A file descriptor is a description of an open file.

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

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,2.

  • 0 is stdin
  • 1 is stdout
  • 2 is stderr

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.

This explanation here goes by way of bash scripting.

To open a file descriptor, you write:

exec 3<> File

To close the 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.

Forking and File Descriptors

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

Sources