What are the default stdin and stdout of a child process?

15,306

Solution 1

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.

Solution 2

The previous answer is correct, but I would encourage you to go further and learn how to use strace. strace attaches to a process and then prints each system call the process is making to your terminal. This can be very educational and maybe a bit overwhelming. Each system call has a man page and you'll see every little action the program is doing in minute detail. It's very useful for debugging problematic processes.

Share:
15,306

Related videos on Youtube

eloone
Author by

eloone

Updated on September 18, 2022

Comments

  • eloone
    eloone over 1 year

    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?

    • S edwards
      S edwards about 8 years
      Interesting question. I wish you'll have an answer
    • Jeff Schaller
      Jeff Schaller about 8 years
    • thoni56
      thoni56 over 4 years
      I wish the OP could accept the answer @James K. Lowden...