Reputation: 48077
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
fork
on same file? That means two processes share a position(offset) information on the same file.Upvotes: 11
Views: 4499
Reputation: 182619
When child process does some read on the file, would the offset of the same file change in parent process?
Yes, since the offset is stored system-wide file table. You could get a similar effect using dup
or dup2
.
If 1 is true, for two processes, is there a convenient way that I can get the same effect of
fork
on same file? That means two processes share a position(offset) information on the same file.
There is a technique called "passing the file descriptor" using Unix domain sockets. Look for "ancillary" data in sendmsg
.
Is there a way to fork so that both processes have totally unrelated tables, like two unrelated processes only that they opened same files.
You have to open
the file again to achieve this. Although it doesn't do what you want, you should also look for the FD_CLOEXEC
flag.
Upvotes: 12