Each process has its own file descriptor table. File descriptor 4 in process 1234 points inside process 1234's table. File descriptor 4 in process 5678 points inside process 5678's table. A case you must be familiar with are file descriptors 0, 1 and 2 which for each process are the standard input, standard output and standard error, pointing wherever these were redirected to.
A process can open the same file more than once. This can happen coincidentally, for example when a process's standard output and standard error are redirected to the same terminal or to the same file. The underlying file table entries (e.g. Linux's struct file
) carry more than information about the file; they also contain opening modes (e.g. read or write) and other state (such as flags, e.g. close-on-exec). For example, a process might have a terminal opened for reading only on file descriptor 0 and that same terminal opened for writing only on file descriptor 2. File tables entries also contain the process's position in the file; a process might want to lseek
to two different positions in the same file, and so would use dup
to obtain two handles to that file.
4
in both processes are relative to it's own number of open fd's. Fd's0-2
(stdin,stdout,sdterr) are always opened for a new process and the numbers are not reserved for only that process. – Jan 05 '12 at 16:04