0

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?

2

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).

  • Thanks. Is feof(3) implemented based on read(2) to detect eof? – Tim Mar 1 '16 at 4:03
  • @Tim - fopen, fread, feof, etc. are library functions implementing stream I/O. These are built on top of the open, read, etc. I/O system calls. – DoxyLover Mar 1 '16 at 5:57
  • @Doxy I knew it, so I asked if feof(3) detects eof by being implemented based on read(2)? – Tim Mar 1 '16 at 6:14
  • Effectively yes. More specifically, fread() calls read() which sets a flag in the stream data structures. Feof() returns that flag. – DoxyLover Mar 1 '16 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.