/*
*用户使用键盘循环输入字符,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 == 0
printf("time out!\n");
printf("tv.tv_sec = %ld\n", tv.tv_sec);
printf("tv.tv_usec = %ld\n", tv.tv_usec);
}
}
return 0;
}
用户使用键盘循环输入字符,select监听终端,将用户输入的字符输出到终端上
最新推荐文章于 2021-08-25 10:14:21 发布