Reputation: 417
I've got a very simple C function below:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
return EXIT_SUCCESS;
}
I use gcc on my linux os terminal to test it.
The result is:
d
d
e
e
f
f
5
5
56
56
I just want to know:
1. Why every time I press my Enter Key, the terminal repeats the character I just typed?
2. Why I put two characters (56), and that works too, how does that work?
3. Why only the Enter Key makes the terminal repeat, not other keys?
4. What does pressing Enter Key mean in a linux terminal or for a C program like this?
Upvotes: 1
Views: 2503
Reputation: 86651
Why every time I press my Enter Key, the terminal repeats the character I just typed?
By default the terminal handler echos everything you type back to you. Your program is also echoing everything you type back to you. You can change this behaviour from the command line with stty, although, to be honest, you might find it confusing. There's also a POSIX C API to do the same which might be more useful.
Why I put two characters (56), and that works too, how does that work?
Every character you type gets sent to the program. Your program reads them all one at a time.
Why only the Enter Key makes the terminal repeat, not other keys?
The normal mode of the terminal program is to buffer characters until a newline is received and then to send them all at once. Your program actually spends most of its time sleeping in getchar()
waiting for characters, then when you press new line, a flurry of activity happens while it processes each of the characters one at a time.
Upvotes: 3
Reputation: 36401
Terminal input is managed through a kernel specific object known as "tty". This tty buffers what you input before (by default) delivering data to your process. This is very useful because it lets you (as a user) correct your command line before sending it to processes. Tty buffering is usually in line-mode, meaning that input data is delivered either if buffer is full or a newline is inputed.
So when you type a single char, that char is not available to your process, it is inside the tty buffer. Then you type a new line and both are available to your process which is then able to read the first one, pushes it to the output then reads the newline and also pushes it to the output.
Tty's behaviour can be changed, see command stty
for example. I encourage you to read about "POSIX terminals".
Upvotes: 8