linux下C实现对键盘事件的监听(按下键盘的时候程序立刻读取)
2016-04-17 15:29
561 查看
#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循环读取键盘效率很低,参考使用异步事件或者多线程技术。单线程为阻塞式的
相关文章推荐
- linux date命令用法
- CentOS 7如何在启动时让网卡连接自动启用
- linux查找目录下的所有文件中是否含有某个字符串
- initrd简介
- Linux--线程的控制与分离
- linux内存源码分析 - 内存回收(匿名页反向映射)
- qemu模拟Cortex-A57运行Linux4.5.1
- 在Linux下信号量的semop操作的sembu结构体中sem_flag的设置值的含义
- linux及安全《Linux内核设计与实现》第四章——20135227黄晓妍
- Linux内核分析第四章 读书笔记
- 几个常用的Linux监控脚本
- Linux内核分析--理解进程调度时机、跟踪分析进程调度和进程切换的过程
- “Linux内核分析”实验报告8
- 《Linux内核分析》 第八节 进程的切换和系统的一般执行过程
- linux中使用lftp上传下载文件
- linux文件权限
- Playing R with GPU accelerated in CentOS 7
- CentOS下搭建自动化测试基础框架:Jenkins+Maven+TestNG+ReportNG
- 《Linux内核设计与实现》第四章读书笔记
- 《Linux内核分析》第八周 进程的切换和系统的一般执行过程