select()用法習得

今天習得了一個Linux內建的神奇小function叫做select()

下面是範例程式

int main(int argc, char *argv[]){
int retsel = 0;
fd_set read_fds;
FD_ZERO(&read_fds);
struct timeval timeout;
init_multi(); //init multicast
FD_SET(multifd, &read_fds); //multifd is the multicast’s FD

while(1)
{
FD_ZERO(&read_fds);
FD_SET(multifd, &read_fds);
timeout.tv_sec = 5; //MUST set timeout everytime before do select
timeout.tv_usec = 0; //MUST set timeout everytime before do select
//select
retsel = select(multifd+1,&read_fds,NULL,NULL,&timeout);

if(retsel == -1)
{ //select error
printf(“select ERROR\n”);
exit(1);
}else if(retsel == 0)
{ //no data after wait 5 secs
printf(“No data to read\n”);
}else
{ //Got something
if(FD_ISSET(multifd,&read_fds))
{
//confirmed received something on net
//do the recvfrom here
}
}
printf(“loop\n”); //for debug
}
//Exit
if(multifd) {close(multifd);} //Tom 20101118 close multicast socket
printf(“End\n”);
return 0;
}

常用在網路相關的應用,碰到他時會嘗試等timeout指定的時間.範例是設定 5.00秒(#13,14).然後遇到select時(#16)會最多等五秒,如果期間內有任何資料傳進來,程式會立刻往下,且retsel會>0,程式會跑到else那段(#26)
如果沒資料,會持續等待到時間到(五秒),然後retsel == 0 (#22),然後又會繼續等下一個五秒.
比較tricky的地方是,那個timeout每次重跑都要重設(#13,14),小宗宗第一次測試時把時間設定放在while迴圈外,所以跑完第一次後就失效,變成select完全無等待的高速while迴圈,所以跑完五秒後瞬間當機XD

搞了好久才發現問題點.分享給大家及自己參考^^