嵌入式linux:getchar() 非阻塞
2016-03-23 15:06
721 查看
#由于getchar()函数会一直阻塞,网上搜到下面的函数来实现非阻塞的读取。实际使用的时候只需要调用kbhit()函数即可。其他函数没有看是什么意思 #include <stdio.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <termios.h> #include <unistd.h> static struct termios ori_attr, cur_attr; static __inline int tty_reset(void) { if (tcsetattr(STDIN_FILENO, TCSANOW, &ori_attr) != 0) return -1; return 0; } static __inline int tty_set(void) { if ( tcgetattr(STDIN_FILENO, &ori_attr) ) return -1; memcpy(&cur_attr, &ori_attr, sizeof(cur_attr) ); cur_attr.c_lflag &= ~ICANON; // cur_attr.c_lflag |= ECHO; cur_attr.c_lflag &= ~ECHO; cur_attr.c_cc[VMIN] = 1; cur_attr.c_cc[VTIME] = 0; if (tcsetattr(STDIN_FILENO, TCSANOW, &cur_attr) != 0) return -1; return 0; } static __inline int kbhit(void) { fd_set rfds; struct timeval tv; int retval; /* Watch stdin (fd 0) to see when it has input. */ FD_ZERO(&rfds); FD_SET(0, &rfds); /* Wait up to five seconds. */ tv.tv_sec = 0; tv.tv_usec = 0; retval = select(1, &rfds, NULL, NULL, &tv); /* Don't rely on the value of tv now! */ if (retval == -1) { perror("select()"); return 0; } else if (retval) return 1; /* FD_ISSET(0, &rfds) will be true. */ else return 0; return 0; } int main() { int tty_set_flag; tty_set_flag = tty_set(); while(1) { if( kbhit() ) { const int key = getchar(); printf("%c pressed\n", key); if(key == 'q') break; } else { fprintf(stderr, "<no key detected>\n"); } } if(tty_set_flag == 0) tty_reset(); return 0; }
相关文章推荐
- 开发板linux到虚拟机linux间的文件传输——scp指令与本地地址的配置
- linux sed 批量替换字符串
- linux下开发android_jni过程及错误经历
- 关于linux 下fcntl()函数的介绍
- linux下read/write编程
- linux下hwclock查询和设置硬件时钟
- Linux环境中查看java的安装路径,设置环境变量
- Centos6.5 卸载mysql
- “Linux内核分析”第五周报告
- linux ubuntu下如何安装并且切换java版本(Unsupported major.minor version 52.0)
- 嵌入式linux的系统搭建与配置
- Linux gzip: stdin: unexpected end of file 硬盘没有空间
- centos7 关闭firewall安装iptables并配置
- debian添加删除用户
- linux路由添加
- Linux 实现自动备份mysql
- linux 常用命令
- Linux命令 crontab
- Dubbo基础篇_01_CentOS安装jdk,Tomact环境
- centos grub安装