How does a program detect the end of stdin input?
There are several ways of providing stdin input to a program.
-
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?
-
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?
-
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? -
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? -
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 startingbc
till exitingbc
considered a stdin input? -
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 returns0
on end-of-file, while stream I/O will probably use thefeof(3)
call. Digging around withstrace
may be necessary to see exactly what some higher-level function likegetline(3)
or specific application is doing under the hood, but most things will probably boil down toread(2)
orfeof(3)
.The heredoc end-label is completely optional in a shell script (though is necessary if other code will follow).