Lets look at the following code:
int main(void)
{
char c;
while ((c = getchar()) != EOF)
putchar(c);
return (0);
}
This program echo’s back the characters, only after a new line is passed as a character.
I tried directly reading using the read system call and passing len as 1, it still reads only when a new line is passed. I have 2 questions here: Who has implemented this optimization, is it the kernel or the terminal/shell?
Secondly, who is echoing back the characters on the first place, that is on the first press itself. Does terminal/shell play any role in the entire execution of this program?
The shell is irrelevant. The tty into which you type (assuming it is not in raw mode, and echoing is enabled ) displays the characters as you type them, but does not pass them to the process until after you type enter. It handles all backspaces and editing etc, and your process never sees those. When you hit enter, the tty passes the entered line to the process.