/* Wait up to 1 min */
tv.tv_sec = 60;
tv.tv_usec = 0;
FD_ZERO(&readfd);
FD_ZERO(&writefd);
for(i=0;i<3;i++)
{
FD_SET(my_rdfd[i], &readfd);
FD_SET(my_wrfd[i], &writefd);
}
for(int i=0;i<10;i++)
{
retval = select((NRFDS)+1, &readfd, &writefd, (fd_set*)0, &tv);//NRFDS is a macro
if (retval == -1)
printf("select() error");
else if (retval)
{
printf("data found\n");
//do something with the data recieved
}
else
printf("Timeout.\n");
}
The thing is that for the first time select() inside the for loop works as expected, fine, for subsequent loops, it doesn't work. What am I doing wrong?
Thank you for your help.
Try putting this within the for loop:
for(i=0;i<10;i++)
{
tv.tv_sec = 60;
tv.tv_usec = 0;
FD_ZERO(&readfd);
FD_ZERO(&writefd);
for(j=0;j<3;j++)
{
FD_SET(my_rdfd[j], &readfd);
FD_SET(my_wrfd[j], &writefd);//Note that you should use a different inside forloop
}
//select statement here
}
When select()
returns, it changes the sets to show which file descriptors have become ready for read/write/exception. All other flags would have been cleared.
It's important that you re-enable the file descriptors that were cleared prior to starting another select, otherwise, you will no longer be waiting on those file descriptors.