Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

non-blocking socket problem 4

Status
Not open for further replies.

bitwise

Programmer
Mar 15, 2001
269
US
I created a UDP socket because the socket is going to be connectionless (i.e. no call to connect() on the socket). I want a non-blocking socket so I added this code:

if(fcntl(sockfd, F_SETFL, O_NONBLOCK) < 0) {
perror(&quot;fcntl()&quot;);
exit(0);
}

This is great; however, it turns out that you can not use a non-blocking socket when using the recvfrom() function. You receive an error message something like this:
&quot;Resource temporarily unavailable&quot;, which corresponds to errno code &quot;EAGAIN&quot;, which means that a client tried to use recvfrom() on a non-blocking socket when no data was available for reading. I thought that was the whole point! Of course there isn't any data &quot;right now&quot; - that is the reason I made the socket non-blocking, so I could handle other events. How am I supposed to do this?

Thanks,
-bitwise
 
What you could do is put the
Code:
recvfrom()
inside a
Code:
select()
loop. You see, the
Code:
select()
statement has a timeout parameter. You could use this.

Code:
struct timeval tv_timeout ;
 .
 .
 .
while (select(..., tv_timeout) != -1) {
    recvfrom (...) ;
}

Hop this helps! [thumbsup] Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.

- janvier -
 
yes.. agree with maluk here

if((rc = select(max(fd, sd) + 1, &readfds, NULL, NULL,NULL/*&tv*/)) <= 0)
{
if(rc < 0)
{
*error_value = errno;
return ERROR__C;
}

}
else
{
if(FD_ISSET(sd, &readfds) > 0)
{
/* Read data from socket */
alen = sizeof(struct sockaddr);
result = recvfrom(sd, buf, READ_BUF_SIZE__C, flag, (struct sockaddr *) &serv_addr, &alen );
if(result < 0)
{
*error_value = errno;
return ERROR__C;
}
else
{
memcpy(&remote_addr[1],&serv_addr.sin_addr.s_addr,4);
*error_value = 0;
*port = ntohs(serv_addr.sin_port);
return result;
}

br:
 
Thanks guys. I had to tweak the code and learn about select() but it was definitely the right direction. Now my loops timeouts after 5 seconds, and I can process other data.

Thanks,
-bitwise
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top