Files & I/O

a file descriptor

Imagine a coat-check counter. You hand over your coat and get back a little numbered ticket. The ticket is not the coat - it is a stand-in you show later to say 'give me the thing I gave you earlier.' A file descriptor is that ticket. When your program opens a file, the operating system does the real work of finding and tracking it, and hands you back a small whole number. From then on you do not pass the file around - you pass that number.

Concretely, a file descriptor is a small non-negative integer, usually starting at 0, 1, 2 and counting up. It is an index into a per-process table the kernel keeps (see the file-descriptor table), where each slot points at the kernel's real bookkeeping for an open file. You get one back from open(), and you hand it to read(), write(), lseek(), and close() to say which open file you mean. By long-standing convention, 0 is standard input, 1 is standard output, and 2 is standard error, so a freshly started program already has those three descriptors open. A descriptor names more than just disk files: pipes, sockets, devices, and terminals all show up as descriptors too.

Why it matters: the file descriptor is the central handle of Unix I/O. Almost every system call that moves bytes in or out takes an fd as its first argument. The number is only meaningful inside the process that owns it - fd 3 in your program and fd 3 in mine refer to completely different things. And because it is just a small integer index, it is cheap to copy, store, and pass to child processes, which is exactly what makes redirection and pipes possible.

int fd = open("notes.txt", O_RDONLY); /* fd might be 3 */ char buf[64]; ssize_t n = read(fd, buf, sizeof buf); close(fd);

open() returns the small integer 3; every later call names the file by that number, not by its path.

A descriptor is just an index, not the file itself. Two descriptors can point at the same open file, and closing one does not affect the other; only when the last reference is closed does the kernel actually release the underlying open file.

Also called
fdfd(檔案描述子)