Frequently Asked Question

What is a file descriptor and why are they numbered 0, 1, and 2?

A file descriptor is a small non-negative integer the kernel uses to identify an open file inside a process. When a program opens a file, socket, pipe, or terminal, the kernel returns a number, and from then on the program passes that number to read, write, and close. Each process has its own table mapping these integers to kernel-side file objects.

The numbers 0, 1, and 2 are reserved for stdin, stdout, and stderr by convention, inherited from Unix in the early 1970s. When a shell starts a new process, it arranges for those three slots to be already populated, usually pointing at the controlling terminal, before exec runs the program. New files opened afterwards get the lowest unused number, typically starting at 3. You can see a process's open descriptors under /proc/<PID>/fd/.

Further reading and video