Timing Out a Read or Write Operation

 < Day Day Up > 



In some applications, it’s important for an application not to block on an I/O operation, but setting the socket to nonblocking means that CPU cycles are wasted in busy-waiting. To combat this problem, the select function can be used to time out the read or write operation. The select function can be used to time out after some duration of no data I/O, permitting the application to perform some other activity. The following example in Listing 6.14 illustrates using the select function to time out after five seconds of awaiting data for read for the given socket.

Listing 6.14 Timing out a read operation.

start example
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> ... int sock, ret; fd_set rfds; struct timeval tv; sock = socket( AF_INET, SOCK_STREAM, 0 ); ... FD_ZERO( &rfds ); FD_SET( sock, &rfds ); tv.tv_sec = 5; tv_tv_usec = 0; ret = select( sock+1, &rfds, NULL, NULL, &tv ); if (ret > 0) {   if ( FD_ISSET( sock, &rfds ) ) {     /* Data is available for read */     ...   } } else {   /* Timeout */   ... }
end example

The select call, as we’ve seen before, uses a bit vector (fd_set structure) to identify the socket descriptors we want to monitor and which action we’re interested in monitoring for. In this case, we specify the read set (argument 2 of the select function). Upon completion of select, the return value represents the number of socket descriptors contained in the resulting set. We can then use the FD_ISSET function to identify which descriptor the event occurred. Otherwise, a zero return from select represents a timeout, which results in whatever application-specific action is necessary.



 < Day Day Up > 



BSD Sockets Programming from a Multi-Language Perspective
Network Programming for Microsoft Windows , Second Edition (Microsoft Programming Series)
ISBN: 1584502681
EAN: 2147483647
Year: 2003
Pages: 225
Authors: Jim Ohlund

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net