File descriptors and /dev/fd

open files

Are file descriptors unique across a process, or throughout the whole system. Because every file seems the use the same descriptor for stdin and stdout. Is there something special with these? How does stdin and stdout work? I realize the dev/fd, is a link to proc/self/fd, but how do they all have the same number?

Edit: Even after looking at other processes most of the file descriptors are about the same numbers.

Best Answer

Several things might be confusing here.

Filedescriptors are attached to a file (in the general sense) and are specific to a given process. Filedescriptors are themselves referred to via numeric ids by their associated process, but one file descriptor can have several ids. Example: ids 1 and 2 which are called standard output and standard error usually refers to the same file descriptor.

The symlinks /proc/pid/fd/x only provide a hint for what the x filedescriptor of process pid is linked to. If it's a regular file, the symlink gives its path. But if the filedescriptor is e.g. an inet socket, then the symlink is just broken. In the case of a regular file (or something which has a path like a tty), it's possible to open it, but you would obtain a different filedescriptor to the same object.

Related Question