select() 调用的剩余时间
我在 Linux/ARM 平台上使用 select()
来查看 udp 套接字是否已收到数据包。 我想知道如果 select 调用在超时之前返回(已检测到数据包),那么 select 调用还剩多少时间。
大致如下:
int wait_fd(int fd, int msec)
{
struct timeval tv;
fd_set rws;
tv.tv_sec = msec / 1000ul;
tv.tv_usec = (msec % 1000ul) * 1000ul;
FD_ZERO( & rws);
FD_SET(fd, & rws);
(void)select(fd + 1, & rws, NULL, NULL, & tv);
if (FD_ISSET(fd, &rws)) { /* There is data */
msec = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
return(msec?msec:1);
} else { /* There is no data */
return(0);
}
}
I'm using select()
on a Linux/ARM platform to see if a udp socket has received a packet. I'd like to know how much time was remaining in the select call if it returns before the timeout (having detected a packet).
Something along the lines of:
int wait_fd(int fd, int msec)
{
struct timeval tv;
fd_set rws;
tv.tv_sec = msec / 1000ul;
tv.tv_usec = (msec % 1000ul) * 1000ul;
FD_ZERO( & rws);
FD_SET(fd, & rws);
(void)select(fd + 1, & rws, NULL, NULL, & tv);
if (FD_ISSET(fd, &rws)) { /* There is data */
msec = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
return(msec?msec:1);
} else { /* There is no data */
return(0);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最安全的做法是忽略
select()
的不明确定义并自己计时。只需获取选择之前和之后的时间,然后从所需的时间间隔中减去该时间即可。
The safest thing is to ignore the ambiguous definition of
select()
and time it yourself.Just get the time before and after the select and subtract that from the interval you wanted.
如果我没记错的话, select() 函数会处理超时和 I/O 参数,并且当 select 返回时,剩余时间会在超时变量中返回。
否则,您必须在调用之前记录当前时间,并在调用之后再次记录当前时间,并获取两者之间的差异。
If I recall correctly, the select() function treats the timeout and an I/O parameter and when select returns the time remaining is returned in the timeout variable.
Otherwise, you will have to record the current time before calling, and again after and obtain the difference between the two.
从 OSX 上的“man select”:
您需要在调用 select 之前调用 gettimeofday,然后在退出时调用 gettimeofday。
[编辑] linux 似乎略有不同:
From "man select" on OSX:
You'll need to call gettimeofday before calling select, and then gettimeofday on exit.
[Edit] It seems that linux is slightly different:
Linux select() 更新超时参数以反映已经过去的时间。
请注意,这不能跨其他系统移植(因此上面引用的 OS X 手册中出现警告),但可以在 Linux 上使用。
吉拉德
Linux select() updates the timeout argument to reflect the time that has past.
Note that this is not portable across other systems (hence the warning in the OS X manual quoted above) but does work with Linux.
Gilad
不要使用 select,尝试在代码中使用大于 1024 的 fd,看看会得到什么。
Do not use select, try with fd larger than 1024 with your code and see what you will get.