终端默认模式为整行ICANON输出模式,先缓存一行再输出,但有时像获取快键键,getch按个键再按个enter就不合适了,这时可以用NONICANON模式,跳过缓存直接输出。
示例
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
int getkey(){int ch;struct termios old, new;tcgetattr( STDIN_FILENO, &old );new = old;new.c_lflag &= ~( ICANON | ECHO );  tcsetattr( STDIN_FILENO, TCSANOW, &new );ch = getchar();tcsetattr( STDIN_FILENO, TCSANOW, &old );return ch;
}int main() 
{int ch;while((ch = getkey())!='q')printf("key  h:%x  d:%d  %c\n",ch,ch,ch);return 0;
}
gcc test.c
&= ~( ICANON | ECHO );
 清除 ICANNON ECHO 标志位
 NONICANON模式 不打印输入
 q键退出