How can same fd in different processes point to the same file?

The file descriptor, i.e. the 4 in your example, is the index into the process-specific file descriptor table, not the open file table. The file descriptor entry itself contains an index to an entry in the kernel's global open file table, as well as file descriptor flags.


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.


Each process has it's own file descriptor table. That's all.

It's all very well described in UNIX Network Programming by Richard Stevens if you would like to learn it deeply.