问题
I am confused about Unix system file tables.
When two or more processes open a file for reading, does the system file table create separate entries for each process or a single entry?
If a single entry is created for multiple processes opening the same file, will their file offsets also be the same?
If
process 1
opensfile1.txt
for reading andprocess 2
opens the same filefile1.txt
for writing, will the system file table create one or two entries?
回答1:
There are three "system file tables": There is a file descriptor table that maps file descriptors (small integers) to entries in the open file table. Each entry in the open file table contains (among other things) a file offset and a pointer to the in-memory inode table. Here's a picture:
(source: rich at www.cs.ucsb.edu)
So there is neither just one file table entry for an open file nor is there just one per process ... there is one per open()
call, and it is shared if the file descriptor is dup()
ed or fork()
ed.
Answering your questions:
1) When two or more processes open a file for reading, there's an entry in the open file table per open. There is even an entry per open if one process opens the file multiple times.
2) A single entry is not created in the open file table for different processes opening same file (but there is just one entry in the in-memory inode table).
3) If file1.txt is opened twice, in the same or two different processes, there are two different open file table entries (but just one entry in the in-memory inode table).
回答2:
The same file may be opened simultaneously by several processes, and even by the same process (resulting in several file descriptors for the same file) depending on the file organization and filesystem. Operations on the descriptors like moving the file pointer, or closing it are independent (they do not affect other descriptors for the same file). Operations of the file (like a write) can be seen by operations on the other descriptors (a posterior read can read the written data).
This is from the open(System call) wiki page
来源:https://stackoverflow.com/questions/14189944/unix-system-file-tables