日期:2014-05-16  浏览次数:21979 次

select返回0的原因大致有哪些
对文件(非socket)操作时,select返回0,即超时,原因都有哪些呢,多谢!

------解决方案--------------------
int select(
int nfds,
fd_set* readfds,
fd_set* writefds,
fd_set* exceptfds,
const struct timeval* timeout
);
本函数用于确定一个或多个套接口的状态,非socket不知怎么用?
select(sock+1,&readfds,0,0,&timeout) 返回0 套接口可读性超时
select(sock+1,0,&writefds,0,&timeout) 返回0 套接口可写性超时
select(sock+1,0,0,&exceptfds,&timeout) 等待带外数据存在性检查超时
select(sock+1,&readfds,&writefds,&exceptfds,&timeout) 返回0 套接口不可用
------解决方案--------------------
超时返回0,没有为什么.
------解决方案--------------------
int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *errorfds, struct timeval *timeout);

需要特别注意的是最后一个参数(超时)不是const的。3楼的写法有问题,虽然有的系统不会修改timeout,但是标准里特别提到:

On successful completion, the object pointed to by the timeout argument may be modified. 

所以在每次select之前,timeout 需要重新赋值。
楼主遇到的问题可能就在这里。

------解决方案--------------------
On Linux, the function select modifies timeout to reflect the amount of time not slept; most other implementations do not do this. 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 selects
in a loop without reinitializing it. Consider timeout to be undefined after select returns.

这个代码的意思是如果是超时返回,那么说明没数据,就再睡2秒的意思,可惜太依赖于实现了,没人保证超时返回timeout还是原值,所以这个代码准确的说是有BUG的,隐患很大。