Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are stdin and stdout made unique to the process?

Stdin and stdout are single files that are shared by multiple processes to take in input from the users. So how does the OS make sure that only the input give to a particular program is visible in the stdin for than program?

like image 302
user2277550 Avatar asked Mar 23 '16 08:03

user2277550


1 Answers

Your assumption that stdin/stdout (while having the same logical name) are shared among all processes is wrong at best.

stdin/stdout are logical names for open files that are forwarded (or initialized) by the process that has started a given process. Actually, with the standard fork-and-exec pattern the setup of those may occur already in the new process (after fork) before exec is being called.

stdin/stdout usually are just inherited from parent. So, yes there exist groups of processes that share stdin and/or stdout for a given filenode.
Also, as a filedescriptor may be a side of a pipe, you need not have file from a filesystem (or a device node) linked to any of the well known standard channels (you also should include stderr into your considerations).

The normal way of setup is:

  • the parent (e.g. your shell) is calling fork
  • the forked process (child) is setting up environment, standard I/O channels and anything else.
  • the child then executes exec to overlay the process with the target image to be executed.

When setting up: it either will keep the existing channels or replace them with new ones e.g. creating a pipe and linking the endpoints appropriately. (To be honest, creating the pipe need to happen before the fork in that simplified description)

This way, most of the process have their own I/O channels.

Nevertheless, multiple processes may write into a channel they are connected to (have a valid filedescriptor to). When reading each junk of data (usually lines with terminals or blocks with files) is being read by a single reader only. So if you have several (running) processes reading from a terminal as stdin, only one will read your typing, while the other(s) will not see this typing at all.

like image 194
rpy Avatar answered Sep 29 '22 12:09

rpy