File descriptors

What is a file descriptor?

A file descriptor (FD) is an identifier for an input/output (I/O) resource in a process.

What kind of resources can a file descriptor reference?

File descriptors can reference many different resources, but the most common are:

  • Regular files (including directories)
  • Block devices
  • Character devices
  • Sockets
  • Pipes
Which values can a file descriptor have?

It has non-negative integer values (0, 1, 2, 3, etc.). If you see a negative value, that means it is not a valid file descriptor and something went wrong when it was read or created.

Are file descriptors unique?

They are unique per process, so different processes referencing the same I/O resource might assign it a different value.

How many file descriptors can a process have?

The number of file descriptors that a process can have is huge, but in practice this figure is usually limited to a few thousand due to security and performance reasons.

Are there any standard file descriptors?

A process usually has at least 3 file descriptors:

Number Name Description
0 Standard Input (STDIN) Input data consumed by the process.
1 Standard Output (STDOUT) Output generated by the process.
2 Standard Error (STDERR) Errors generated by the process.
What tools can I use to work with file descriptors?

There are 2 main tools you can use to list file descriptors:

  • lsof: list open files. This is the most common tool and the one you will find everywhere, even in other Unix-like operating systems like macOS.
  • lsfd: list file descriptors. This is a more modern and specialized Linux-only tool.
Where can I find more info about file descriptors?

Man pages:

man lsof
man lsfd

External links: