我使用 select 进行同步 I/O 多路复用。它将检查任何数据 1 秒。1 秒后如果没有数据,它将显示输出 (puts("Waited for 1 sec no data");
) 然后它会再次检查数据。但这只在第一次工作然后它进入无限循环。
是否有任何替代解决方案。
//..............................
//.............................
//Creating listener socket and other sort of things
struct timeval tv;
tv.tv_sec=1;
tv.tv_usec=0;
while(1)
{
FD_ZERO(master);
FD_SET(listener,master);
fdmax = listener;
int retval=select(fdmax+1,master, NULL, NULL,&tv);
printf("retval is %d\n",retval);
if(retval == -1)
{
perror("Server-select() error");
}else if(retval)
{
puts("Data available");
//If there is no data do some work and checkagain.
}else
{
puts("Waited for 1 sec no data");
//If there is no data do some work and checkagain.
}
}
最佳答案
来自 man select :
On Linux, select() modifies timeout to reflect the amount of time not slept; most other implementations do not do this. (POSIX.1-2001 permits either behavior.) This causes problems both when Linux code which reads timeout is ported to other operating systems, and when code is ported to Linux that reuses a struct timeval for multiple select()s in a loop without reinitializing it. Consider timeout to be undefined after select() returns.
所以像 master
一样,您必须在每次 select
调用之前设置 tv
。
在我的代码中,我经常有这样的东西:
FD_ZERO(master);
FD_SET(listener,master);
fdmax = listener;
while (1)
{
struct timeval tv = {1, 0};
int retval=select(fdmax+1,master, NULL, NULL,&tv);
printf("retval is %d\n",retval);
if(retval == -1) {
perror("Server-select() error");
break; // <-- notice the break here
} else if(retval) {
puts("Data available");
} else {
puts("Waited for 1 sec no data");
}
}
关于c - 如何在 C 中超时后调用选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36786460/