is there a simple way to set a timeout on the recvfrom() function?
Printable View
is there a simple way to set a timeout on the recvfrom() function?
Yeah, using the select() function.
EDIT:
Here is a site with a good explanation on its use.
http://www.lowtek.com/sockets/select.html
I found an example I like better than the one In the link I posted:
Code:SOCKET theSocket;
struct timeval stTimeOut;
fd_set stReadFDS;
fd_set stExcepFDS;
fd_set stWriteFDS;
FD_ZERO(&stReadFDS);
FD_ZERO(&stExcepFDS);
FD_ZERO(&stWriteFDS);
// Timeout of one second
stTimeOut.tv_sec = 1;
stTimeOut.tv_usec = 0;
FD_SET(theSocket, &stReadFDS);
FD_SET(theSocket, &stExcepFDS);
FD_SET(theSocket, &stWriteFDS);
int test = 0;
char szBuf[256];
memset(szBuf, ' ', sizeof(szBuf));
while (true) {
int t = select(-1, &stReadFDS, &stWriteFDS, &stExcepFDS, &stTimeOut);
if (t = SOCKET_ERROR) {
fprintf(stderr, "Call to select() failed");
exit(1);
}
if (t != 0) {
printf("Something to do...");
if (FD_ISSET (theSocket, &stExcepFDS)) {
printf("Exception flag is set");// Deal with this
}
if (FD_ISSET(theSocket, &stReadFDS)) {
printf("There is data pending to be read..."); // Read data with recv()
}
if (FD_ISSET(theSocket, &stWriteFDS)) {
printf("There is data pending to be written...");// Send Data with send()
}
}
else {
printf("t is zero");
exit(1);
}
}
i've been reading on select() and i do understand the "reading" part, but what's with the "writing" and "exception"?
For what you are looking for, you only care about reading.
Change the select line to:
select(-1, &stReadFDS, 0, 0, &stTimeOut);
Then if select returns a number greater than 0, there is data to be read from the socket. If select returns 0, there was nothing to read and the call timed out.
Since when was passing -1 to select a good idea?
It's supposed to be the max file descriptor in all the sets, plus 1
Read the MSDN docs:
http://msdn.microsoft.com/library/de...k/select_2.asp
In winsock, that parameter is ignored. Since the poster didnt specify a platform, I assumed windows (as is evident by the SOCKET structure in my example).
well i read the msdn, but isn't writefds kinda stupid? because i can just check if connect() failed with and if statment, no?
You dont need to check for writefds. Read my last post :)
Quote:
For what you are looking for, you only care about reading.
Change the select line to:
Code:select(-1, &stReadFDS, 0, 0, &stTimeOut);
i understand that, but still when will i need it?
Well keep in mind that select() works on more than just sockets. It can also work on regular file descriptors as well.
MS select does not work on non-socket file descriptors
ok, but the standart berkley select() does? can you give me an example?
> can you give me an example?
I'd be surprised if a board search didn't turn up at least one example