引自:linux下C实现对键盘事件的监听(按下键盘的时候程序立刻读取)
- #include <termio.h>
- #include <stdio.h>
-
-
- int scanKeyboard()
- {
- int in;
- struct termios new_settings;
- struct termios stored_settings;
- tcgetattr(0,&stored_settings);
- new_settings = stored_settings;
- new_settings.c_lflag &= (~ICANON);
- new_settings.c_cc[VTIME] = 0;
- tcgetattr(0,&stored_settings);
- new_settings.c_cc[VMIN] = 1;
- tcsetattr(0,TCSANOW,&new_settings);
-
- in = getchar();
-
- tcsetattr(0,TCSANOW,&stored_settings);
- return in;
- }
-
- //这个方法就可以,返回值是该键的ASCII码值,不需要回车的,
- //测试函数
- int main(){
- while(1){
- printf(":%d",scanKeyboard());
- }
- }
通过tcsetattr函数设置terminal的属性来控制需不需要回车来结束输入。
更详细的参考 man 3 tcgetattr
ICANON
Enable canonical mode. This enables the special characters EOF, EOL, EOL2, ERASE, KILL, LNEXT, REPRINT, STATUS, and WERASE, and buffers by lines.
可以看出ICNAON标志位启用了整行缓存。
所以,new_settings.c_lflag &= (~ICANON);这句屏蔽整行缓存。那就只能单个了。
另外一个可运行的例子:http://blog.csdn.net/alangdangjia/article/details/27697721
注:通过while循环读取键盘效率很低,参考使用异步事件或者多线程技术。单线程为阻塞式的