This question already has an answer here:

Since shell (for example, Bash) is just another program with its own stdin/stdout/stderr streams, how does it deliver user's input to running program? Here's simple program, that reads value from stdin and prints to stdout:

// main.c

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main() {
    char s[256];
    printf("Scanning value...\n");
    scanf("%s", s);
    printf("Printing value...\n");
    printf("%s\n", s);

    return 0;

If we compile this program (gcc -o main main.c) and run from bash ./main, what exactly bash does with program's input/output after forking? I guess the pseudocode would look like this:

    int pid = fork();
    if (pid == 0) {
        // do something with copied file descriptors, like redirecting or piping I guess
    } else if (pid > 0) {
        // wait for terminating runned process
    } else {
        printf("Error creating new process\n");

I tried to use lsof -p <main's pid>, and it showed me, that all stdin, stdout, stderr file descriptors leads to /dev/pts/6 file. But if program writes to this file (not file really, but some device), how can program read from this file, not messing with output?

So, the question is: what exactly shell does with program's input and output to be able to deliver user's input to program and to show program's output on screen?

marked as duplicate by muru, Mr Shunz, Stephen Kitt bash Apr 11 at 9:34

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Browse other questions tagged or ask your own question.