Nonblocking Sockets

 < Day Day Up > 



Let’s first understand the difference between blocking and nonblocking semantics. In a typical system, when a call is made to a socket read function such as recv, if no data is available to be read at that time, the socket blocks. By blocking, we mean that the call pends and does not return until either data is available to read or an error occurs. Therefore, the return of the recv call may happen quickly, or it may take a long time; it’s very dependent upon data to read. This standard behavior can be altered to the reverse semantics, or nonblocking. In nonblocking semantics, functions return immediately and do not block (or pend) awaiting some action to be performed. This means that a call to recv will return an error if no data is available to read. The error message returned is commonly EWOULDBLOCK, which means that the call would normally block, but due to the nonblocking nature of the socket, blocking is disallowed and the resulting error is returned.

Making sockets nonblocking is very implementation dependent. Some stacks provide socket options to enable nonblocking behavior. Unix systems provide an ioctl call to change the blocking nature of a socket. Consider the following example in Listing 6.2.

Listing 6.2 Making a socket nonblocking on a Unix system.

start example
int sock, mode, ret; #define BLOCKING          0 #define NONBLOCKING       1 sock = socket( AF_INET, SOCK_STREAM, 0 ); mode = NONBLOCKING; ret = ioctl( sock, FIONBIO, &mode );
end example

Nonblocking sockets are useful for performance and are commonly assisted by the use of the select call for I/O multiplexing.



 < 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