/*
*用户使用键盘循环输入字符,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;
}
/*akaedu@akaedu-G41MT-D3:~/桌面/T74_system/0820_chp1_dup2_select$ ./select2
a
a
x
x
time out!
tv.tv_sec = 0
tv.tv_usec = 0
time out!
tv.tv_sec = 0
tv.tv_usec = 0
d
d
time out!
tv.tv_sec = 0
tv.tv_usec = 0
^C
akaedu@akaedu-G41MT-D3:~/桌面/T74_system/0820_chp1_dup2_select$
*/
<pre name="code" class="cpp">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#define N 1024
#define FOUND "found data! It's:"
int main(void)
{
fd_set rfds;
struct timeval tv;
int retval, n;
int max_fd; //所关心的最大文件描述符
char buf[N];
FD_ZERO(&rfds); //将可读文件描述符集合清零
FD_SET(STDIN_FILENO, &rfds); //将(fd 0)添加到集合中
max_fd = STDIN_FILENO; //只关心标准输入
tv.tv_sec = 5; //等待超时上限设置为5秒
tv.tv_usec = 0;
//只关心可读集合
retval = select(max_fd+1, &rfds, NULL, NULL, &tv);
if(retval == -1){ //返回-1说明出错,errno会被设置
perror("select error");
exit(1);
}else if(retval > 0){//监听集合中,改变个数大于0
if(FD_ISSET(STDIN_FILENO, &rfds)){ //所关心的仍应在集合中
n = read(STDIN_FILENO, buf, N);
if(n == -1){
perror("read error");
exit(1);
}
write(STDOUT_FILENO, FOUND, strlen(FOUND));
write(STDOUT_FILENO, buf, n);
}
}else //在指定时间范围内没有数据到达
printf("time out... no data arrive\n");
return 0;
}
/*akaedu@akaedu-G41MT-D3:~/桌面/T74_system/0820_chp1_dup2_select$ ./select1
a
found data! It's:a
akaedu@akaedu-G41MT-D3:~/桌面/T74_system/0820_chp1_dup2_select$ ./select1
time out... no data arrive
akaedu@akaedu-G41MT-D3:~/桌面/T74_system/0820_chp1_dup2_select$
*/
selsect 函数(一)
最新推荐文章于 2021-04-23 10:57:33 发布