logo

Linux - File Descriptor

In Linux (and other Unix-like systems), a File Descriptor (FD) is a non-negative integer that serves as a unique identifier for an open file or I/O resource within a specific process.

Think of it as a temporary "handle" or a pointer that the operating system gives to a program so the program can talk to a resource without needing to know its physical location on the disk or its hardware address.

How it Works

In Linux, "everything is a file." This means file descriptors are used to access:

  • Regular files (text files, images, binaries).
  • Directories.
  • Pipes (for communication between processes).
  • Sockets (for network communication).
  • Devices (like your keyboard, mouse, or hard drive).

When a process wants to open a file, it makes a system call (like open). If successful, the kernel creates an entry in the process's File Descriptor Table and returns the smallest available integer (the FD) to the process.

The Standard File Descriptors

Every new process starts with three standard file descriptors automatically opened for it:

Integer Name Description
0 stdin Standard Input (usually the keyboard)
1 stdout Standard Output (the terminal screen)
2 stderr Standard Error (error messages on the screen)

Any files you open after these will typically start at FD 3, then 4, and so on.

Is it Ephemeral?

Yes, file descriptors are ephemeral. A file descriptor (FD) is only available while the associated resource is open within a specific process.

They are temporary in several ways:

  1. Scope is Per-Process: An FD only has meaning within the process that opened it. If Process A has FD 5 open for a text file, and Process B has FD 5 open, they are likely pointing to completely different things.
  2. Lifetime is Tied to the Process: When a process terminates (closes or crashes), the kernel automatically closes all of its open file descriptors and reclaims those numbers.
  3. They do not survive reboots: Because FDs live in the system's RAM (within the kernel's process tables), they disappear as soon as the system is powered down.
  4. Numbers are Recycled: As soon as you close() a file descriptor, that integer becomes available for the kernel to assign to the next file or socket you open.

Is FD per process?

Yes, File Descriptors are strictly per-process.

Each process has its own private File Descriptor Table managed by the kernel. The integer (the FD) is simply an index into that private table.

How is FD stored in kernel?

Every process has its own task_struct in the kernel, which contains a pointer to a files_struct. This is a private array where the index is the FD number.

If a file is open multiple times, it may have different fd?

Exactly. If you call open() on the same file twice, the OS will give you two different file descriptors.