一个linux控制台程序demo
2014-04-03 15:32
183 查看
这个demo可以一边中期性地处理业务一边跟用交互。其中doWork()函数表示程序业务,interaction()函数负责跟用户交互,它确保在用户按下键盘的时候,程序会有相应。按下q键程序会结束。
这里假设dowork()内的工作用时是很短的,对用户来说可以忽略不计。
要保证在用户按下键盘按键时程序立即能够接收到,而不需要再按回车键,需要对终端属性进行一些修改,参考:linux下的getch模拟(无回显读取字符)
代码如下:
参考资料:
无阻塞监听函数select():http://baike.baidu.com/subview/621719/11844440.htm?fr=aladdin
这里假设dowork()内的工作用时是很短的,对用户来说可以忽略不计。
要保证在用户按下键盘按键时程序立即能够接收到,而不需要再按回车键,需要对终端属性进行一些修改,参考:linux下的getch模拟(无回显读取字符)
代码如下:
#include<stdio.h> #include<string.h> #include<sys/time.h> #include<stdlib.h> #include<termios.h> int goOn = 1; void doWork(){ printf("---------I am working....\n"); } void interaction(int delay){//delay seconds // 修改终端属性,保证按键被立即接收 struct termios save, current; tcgetattr(0, &save); current = save; current.c_lflag &= ~ICANON; current.c_lflag &= ~ECHO; current.c_cc[VMIN] = 1; current.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, ¤t); // 在delay指定的时间内,接收用户按键 int entertime = time(NULL); while(delay > 0){ int now = time(NULL); delay -= now - entertime; fd_set readfds; FD_ZERO(&readfds); FD_SET(0, &readfds); struct timeval timeout; if(delay > 0){ timeout.tv_sec = delay; timeout.tv_usec = 0; }else break; char ch; switch(select(32, &readfds, NULL, NULL, &timeout)){ case 0: // printf("select time out\n"); break; case -1: // printf("select error\n"); break; default: // 在这里写跟用户交互的代码 if((ch = getchar()) == 'q'){ tcsetattr(0, TCSANOW, &save); goOn = 0; return; } printf("ch=%c\n", ch); } } tcsetattr(0, TCSANOW, &save);// 恢复原来的终端属性,以免干扰shall和之后的程序运行 } int main(){ while(goOn){ doWork(); interaction(3); } }
参考资料:
无阻塞监听函数select():http://baike.baidu.com/subview/621719/11844440.htm?fr=aladdin
相关文章推荐
- Linux设备驱动程序学习(12)-Linux设备模型(底层原理简介)
- Linux设备驱动程序学习(3-补)-Linux中的循环缓冲区
- Linux设备驱动程序学习(11)-中断处理
- linux系统编程之信号(七):被信号中断的系统调用和库函数处理方式
- Linux设备驱动程序学习(9)-与硬件通信
- Linux设备驱动程序学习(8)-分配内存
- Linux设备驱动程序学习(6)-高级字符驱动程序操作[(4)异步通知fasync]
- Linux设备驱动程序学习(6)-高级字符驱动程序操作[(3)设备文件的访问控制]
- Linux设备驱动程序学习(5)-高级字符驱动程序操作[(2)阻塞型I/O和休眠]
- Linux设备驱动程序学习(4)-高级字符驱动程序操作[(1)ioctl and llseek]
- linux快速搭建vsftpd服务以及常见问题
- Linux常用命令征集
- LInux 描述符GDT, IDT & LDT结构定义
- linux配置网卡
- Linux设备驱动程序学习(7)-内核的数据类型(深入分析Linux内核链表)
- linux常用命令大全
- Linux设备驱动程序学习(7)-内核的数据类型
- linux硬盘分区方案
- Linux设备驱动程序学习(10)-时间、延迟及延缓操作(Jiq.c)
- Linux设备驱动程序学习(10)-时间、延迟及延缓操作(Jit.c)