select() 当有一些数据要读取时阻塞
select() blocks when there are some data to read
我正在尝试在串行端口上实现阻塞读取。我有以下代码
int blocking_read(int input_fd,int wait_time){
if(wait_time <= 0) return 0;
fd_set set;
FD_ZERO(&set);
FD_SET(input_fd,&set);
struct timeval wait_time_struct;
wait_time_struct.tv_sec = wait_time / 1000000;
wait_time_struct.tv_usec = wait_time % 1000000;
int ret = select(1,&set,NULL,NULL,&wait_time_struct);
char a;
int check=read(input_fd,&a,1);
printf ("ret %d, check %d %02x\n",ret,check,a&0xFF);
return ret;
}
最后 4 行仅用于调试...
当我 运行 这个当我期望循环中串口上的消息时,输出是:
ret 0, check 1 ff
ret 0, check 1 ff
ret 0, check 1 c4
ret 0, check 1 d7
ret 0, check 1 00
ret 0, check 1 01
...
我期望的消息是 FF FF C4 D7 00 01....
很明显,select()
块即使有东西要读...你能帮帮我吗?
我应该这样使用 select:
int ret = select(input_fd +1,&set,NULL,NULL,&wait_time_struct);
参数名称 nfds 让我有点困惑,它看起来就像集合中的一些文件描述符。来自手册
nfds is the highest-numbered file descriptor in any of the three sets, plus 1.
我正在尝试在串行端口上实现阻塞读取。我有以下代码
int blocking_read(int input_fd,int wait_time){
if(wait_time <= 0) return 0;
fd_set set;
FD_ZERO(&set);
FD_SET(input_fd,&set);
struct timeval wait_time_struct;
wait_time_struct.tv_sec = wait_time / 1000000;
wait_time_struct.tv_usec = wait_time % 1000000;
int ret = select(1,&set,NULL,NULL,&wait_time_struct);
char a;
int check=read(input_fd,&a,1);
printf ("ret %d, check %d %02x\n",ret,check,a&0xFF);
return ret;
}
最后 4 行仅用于调试... 当我 运行 这个当我期望循环中串口上的消息时,输出是:
ret 0, check 1 ff
ret 0, check 1 ff
ret 0, check 1 c4
ret 0, check 1 d7
ret 0, check 1 00
ret 0, check 1 01
...
我期望的消息是 FF FF C4 D7 00 01....
很明显,select()
块即使有东西要读...你能帮帮我吗?
我应该这样使用 select:
int ret = select(input_fd +1,&set,NULL,NULL,&wait_time_struct);
参数名称 nfds 让我有点困惑,它看起来就像集合中的一些文件描述符。来自手册
nfds is the highest-numbered file descriptor in any of the three sets, plus 1.