What are the default stdin and stdout of a child process

processstdinstdout

I would like to know what are the default stdin and stdout of a child process (if there are such defaults). Are stdin and stdout of a child process the same as its parent process? Is this something inherited from the parent or something set by the parent? Or are the stdin and stdout of the child process plugged into stdin and stdout of parent process?

In my understanding parent and child are not piped but are at first clones, so I think stdin and stdout of the child are exactly the same as the parent, but I am not sure.

For example, in a terminal running bash as a login shell, if I type shit will create a child shell process, that will have as stdin the keyboard and stdout the terminal screen, so the same as its parent. I want to understand how the child's stdin and stdout were defined and what they are.

I want to know if for example in this case, if the stdin and stdout of the child are like the parent's it's because parent's stdin is piped into child stdin, and parent just "redirects" its input to the child or if the child gets its input directly from the keyboard.

In this same case, if parent and child have the same stdin, does that mean that the parent processes the same commands that are typed to the child? How come we only see the stdin/out of child in the terminal and not its parent's?

Best Answer

Look at the man page for fork(2). A child process inherits the parent's file descriptors, including standard input and standard output. For a single command, the shell simply lets the child process inherit those descriptors and write its output to the terminal. For a pipeline, it forks each process, sets up a pipe between the output of one and the input of the next, and then executes (exec(2)) each child's executable.

Related Question