select用法

select用法 

select为linux常用的非堵塞套接字API,原型为:

int select(int nfds, fd_set *readfds, fd_set *writefds,

              fd_set *exceptfds, struct timeval *timeout);

select用于检测文件描述符的变化,参数五timeout:

1. NULL传入,此时select置于堵塞状态,直到fd发生变化函数才返回。

2. 时间值设为0秒0纳秒,不管fd是否变化,函数立即返回。

3. timeout值大于0,就是等待超时时间。如超时时间内有事件到来就返回,否则在超时后再返回。

struct timeval tm;
tm.tv_sec = 1;
tm.tv_usec = 0;

while(1)
{
	int num = select(maxfd,rfd,NULL,NULL,&tm);
	... 
}

   执行上述,发现CPU占用率100%。也就是说tm未起到作用。调试过程中,第一次执行select()时超时1s,但是第二次执行时立即返回,发现此时 tm.tv_sec 变为0了,导致select立即返回后。为降低CPU占用,因此每次调用前更新tm变量。

while(1)
{
	// 每次设置时间
	tm.tv_sec = 1;
	int num = select(maxfd,rfd,NULL,NULL,&tm);
	... 
}

猜你喜欢

转载自tcspecial.iteye.com/blog/2252468