Reputation: 2075
I'm getting a strange result while experimenting with select().
fd_set tempset,set; //set of descriptors
FD_ZERO(&set); //initialize descriptor set to NULL
FD_SET(serversock,&set); //add server's socket to descriptor set 'set'
timeout.tv_sec=2;
timeout.tv_usec=0;
while(1){
tempset=set;
timeout.tv_sec=2;
timeout.tv_usec=0;
printf("%s","Waiting on select\n");
int ret=select(FD_SETSIZE,&tempset,NULL,NULL,&timeout);
if(ret==0) printf("timeout ");
else if(ret==-1){
printf("Error occured\n");
exit(0);
}
else if(ret>0){ //socket ready for reading
for(i=0;i<FD_SETSIZE;i++){
if(FD_ISSET(i,&tempset)){ //check if it's serversock
if(i==serversock){
//accept connection and read/write
printf("Client connected\n");
}//i==serversock close
}
}//for ends
}
When I remove the the line printf("%s","Waiting on select\n"); select keeps waiting indefinitely. However, when I reinsert the line, everything works as expected (tested with a client connection)
Am I missing something?
Upvotes: 1
Views: 909
Reputation: 595349
You are misususing FD_SETSIZE
, which you should not be using directly at all. You are only putting one socket into the fd_set
, so there is no need to even loop through it at all (but if you did need to, use the fd_set.fd_count
member instead).
Try this:
fd_set set;
timeval timeout;
while(1){
FD_ZERO(&set);
FD_SET(serversock, &set);
timeout.tv_sec = 2;
timeout.tv_usec = 0;
printf("%s","Waiting on select\n");
int ret = select(serversock+1, &set, NULL, NULL, &timeout);
if (ret==0){
printf("timeout ");
}
else if (ret==-1){
printf("Error occured\n");
exit(0);
}
else if (ret>0){ //socket ready for reading
... = accept(serversock, ...);
printf("Client connected\n");
}
}
Or:
fd_set set;
timeval timeout;
int max_fd = 0;
while(1){
FD_ZERO(&set);
FD_SET(serversock, &set);
max_fd = serversock;
// FD_SET() other sockets and updating max_fd as needed...
timeout.tv_sec = 2;
timeout.tv_usec = 0;
printf("%s","Waiting on select\n");
int ret = select(max_fd+1, &set, NULL, NULL, &timeout);
if (ret==0){
printf("timeout ");
}
else if (ret==-1){
printf("Error occured\n");
exit(0);
}
else if (ret>0){ //socket(s) ready for reading
for (u_int i = 0; i < set.fd_count; ++i){
... = accept(set.fd_array[i], ...);
printf("Client connected\n");
}
}
}
Upvotes: 4