Bash – How Does a Program Detect the End of stdin Input?

bashstdin

How does a program detect the end of stdin input?

There are several ways of providing stdin input to a program.

  1. When using here-document, we specify a delimiter to signal the end
    of stdin input:

    <<[−]word
    here-document
    delimiter
    

    Why do we need to explicitly specify the end of stdin input?

  2. When using here string, there is no extra effort to signal the end
    of stdin input:

    <<< word
    

    How does the program knows the end of stdin input?

  3. When using redirection from a file to stdin, there is no extra
    effort to signal the end of stdin input. How does the program knows
    the end of stdin input?

  4. When using pipe to direct stdout output from another program to the stdin input of the program, there is no extra effort to signal the end of stdin input?
    How does the program knows the end of stdin input?

  5. In some programs, such as bc, whenever you enter an arithmetic expression and hit return, it will takes in the expression as stdin input and output the evaluated result. In such case, is each line ended by return considered a whole stdin input, or are all the lines typed from starting bc till exiting bc considered a stdin input?

  6. What is the general principle that a program knows how to detect the
    end of stdin input?

    When do we need to specify the end of stdin input explicitly like
    for here-document, and when do we need not?

    Are they program-dependent, or program-independent?

Best Answer

This depends on the specific system calls a process uses; read(2) on a file descriptor returns 0 on end-of-file, while stream I/O will probably use the feof(3) call. Digging around with strace may be necessary to see exactly what some higher-level function like getline(3) or specific application is doing under the hood, but most things will probably boil down to read(2) or feof(3).

The heredoc end-label is completely optional in a shell script (though is necessary if other code will follow).

Related Question