用户使用键盘循环输入字符,select监听终端,将用户输入的字符输出到终端上

来源:互联网 发布:功夫熊猫 知乎 编辑:程序博客网 时间:2024/04/29 01:49
/* *用户使用键盘循环输入字符,select监听终端,将用户输入的字符输出到终端上 *如果用户指定时间内没有做输入,提示超时,用户输入‘q’退出。 */#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#include <fcntl.h>#include <sys/select.h>int main(void){fd_set rfds, inset;struct timeval tv;int retval, n, max_fd;char ch;max_fd = open("/dev/tty", O_RDONLY);if(max_fd < 0){perror("open /dev/tty error");exit(1);}FD_ZERO(&rfds);FD_SET(max_fd, &rfds);while(1){tv.tv_sec = 3;//每个字符都设置一次超时上限tv.tv_usec = 600;//所以这个应该至于循环中inset = rfds;//***保证监听的文件描述符始终在集合中retval = select(max_fd+1, &inset, NULL, NULL, &tv);if(retval == -1){perror("select error");exit(1);}else if(retval){//retval>0说明监听的集合中有改变if(FD_ISSET(max_fd, &inset)){//所关心的文件应在集合中n = read(max_fd, &ch, 1);if(n < 0){ perror("read error"); exit(1); }if('q' == ch){ break; }if('\n' == ch){//用户直接回车,忽略其操作continue;}write(1, &ch, n);putchar('\n');//printf("tv.tv_sec = %ld\n", tv.tv_sec);//printf("tv.tv_usec = %ld\n", tv.tv_usec);continue;}}else{//retval == 0printf("time out!\n");printf("tv.tv_sec = %ld\n", tv.tv_sec);printf("tv.tv_usec = %ld\n", tv.tv_usec);}}return 0;}

0 0
原创粉丝点击