Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To execute your program, the shell calls fork(2) to create a child process, and in the child process calls exec(3) to replace itself with the "dummy" program.</p> <p>I imagine there is something like this in the shell's source code (if it is written in C):</p> <pre><code>if (fork() == 0) execlp(program, arguments) </code></pre> <p>The child process inherits the file descriptors of the parent; in this case the shell. So the child process has the same stdin/stdout as the shell that exec'd it, which is the virtual terminal.</p> <p>I'm not sure exactly how, but I'd imagine the parent process (the original shell you typed the command in) disregards stdin somehow whilst the child process is running. </p> <p>When the program exits, the shell gets its stdin back. Any extra characters that weren't read by the your program will go to the shell. And then of course the shell just treats them as a command.</p> <p>If you try using fgetc(3) instead of read(2) at first it appears the extra characters are lost, not sent to the shell... <em>but</em>, if you unbuffer stdin, you get the same effect using fgetc(2), ie: extra characters go back to the shell.</p> <pre><code>char rbuf[100]; setbuf(stdin, NULL); // with this line - same effect as using read(2) // without it - extra characters are lost for (int i = 0; i &lt; 5; ++i) rbuf[i] = (char)fgetc(stdin); </code></pre> <p>By default stdin is line buffered. So it looks like this behaviour is avoided when using buffered stdin because the entire line is read, and extra characters are discarded, whereas unbuffered stdin (or low level reads) will not read until the end of the line, and extra characters remain to be read by the parent (shell) once your program exits.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload