Unix kernel represents open files using three data structures: Descriptor table, File table, and v-node table.
When a process opens a file twice, it gets two different descriptors in the descriptor table, two entries in the file table(so that they have different positions in the same file), and they both point to one entry in the v-node table.
And child process inherits parent process’s descriptor table, so kernel maintains one descriptor table for each process respectively. But two descriptor from different processes point to the same entry in open file table.
So
- When child process does some read on the file, would the offset of the same file change in parent process?
- If 1 is true, for two processes, is there a convenient way that I can get the same effect of
forkon same file? That means two processes share a position(offset) information on the same file. - Is there a way to fork so that both processes have totally unrelated tables, like two unrelated processes only that they opened same files.
Yes, since the offset is stored system-wide file table. You could get a similar effect using
dupordup2.There is a technique called “passing the file descriptor” using Unix domain sockets. Look for “ancillary” data in
sendmsg.You have to
openthe file again to achieve this. Although it doesn’t do what you want, you should also look for theFD_CLOEXECflag.