当您键入时,控制台会抓取键盘的输出,并将其回显给您。
getchar() 对输入流进行操作,该输入流通常配置为打开“规范输入”。这种配置减少了 CPU 轮询输入以获取缓冲方案的时间,在该方案中输入被缓冲,直到某些事件发生,通知缓冲区扩展。按下回车键(并按下控制 D)都倾向于刷新该缓冲区。
#include <unistd.h>
int main(void){
int c;
static struct termios oldt;
static struct termios newt;
/* Fetch the old io attributes */
tcgetattr( STDIN_FILENO, &oldt);
/* copy the attributes (to permit restoration) */
newt = oldt;
/* Toggle canonical mode */
newt.c_lflag &= ~(ICANON);
/* apply the new attributes with canonical mode off */
tcsetattr( STDIN_FILENO, TCSANOW, &newt);
/* echo output */
while((c=getchar()) != EOF) {
putchar(c);
fflush(STDOUT_FILENO);
}
/* restore the old io attributes */
tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
return 0;
}