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循环读取键盘效率很低,参考使用异步事件或者多线程技术。单线程为阻塞式的




  • 15
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值