views:

17

answers:

1

I have a question in mind. By convention, unix associates the file descriptor 0, 1, 2 for stdin, stdout, stderr on every process. Is the file, e.g. pointed by stdin, shared by different processes? If shared, when we open two shells to type some inputs to these two shells, how is the os doing to manage the shared file?

+1  A: 

Overview

The descriptor table is per-process, so it's possible for every process in the system to have a different file open in every descriptor table slot

But in practice it's a bit more complex. If two processes open a file independently, then they each have completely separate access to the file, with their own read and write pointers, and they will only interact if they both write to the same file.

But when a process fork(2)'s, then the parent and child's descriptors point to the same file table entry, and so they share a single position in the file. This enables Unix processes to share access to an input stream without needing to be aware of the situation.

Three Tables

Access to files is chained through three important tables in Unix. The descriptor table is per-process and points to the file table. Think of the file table as the open file table. There is a third table, originally called the inode table that manages access to actual files.

The key thing to realize is that while there is never more than one entry in the inode table for any one file, there may or may not be multiple entries in the file table. If a file descriptor is created with open(2) then the inode gets a new file table entry, but if it's created with fork(2) then the same file table entry is reused and the read and write pointers are shared.

So, two shells...

In the case of two shells with two different windows for typing, or two shells running different scripts, then they aren't using the same file at all, or if it's the same script, it was opened twice so their positions are independent. Both may be file descriptor "0" within each process but that's because every process has its own descriptor table.

DigitalRoss
HI, DigitalRoss, thank you for your answer. But I am a bit confused by your description. so for parent/child processes, they shared their fd table points to the same files. this is clear. But, for different processes with the stdin set to the same file, e.g. by python, pA=subprocess.Popen(stdin='file'); pB=subprocess.Popen(stdin='file'); in this case, they have separate accesses to read 'file'? how exactly? each one has a temporary buffer with the opened file? is this the same approach as for the case of two shells that are given the same script as stdin
pepero
1. Yes. 2. See my updated answer above. 3. Sort of. 4. Yes.
DigitalRoss
DigitalRoss, thank you for your answer and more explanation
pepero