Chapter 13. Nonblocking I/O By default, on most operating systems I/O is blocking. If a request to read or write some data can't be satisfied immediately, the operating system puts the program to sleep until the call completes or generates an error. For most programming tasks , this does not cause a problem, because disk drives , terminal windows , and other I/O devices are relatively fast, at least in human terms. As we saw in the last chapter, however, blocking presents a problem for client/server programming because a single blocked network call can make the whole program hang while other requests wait. To mitigate the effect of blocking in read or write calls, one can either have several concurrent threads of execution, as with forking and multithreading servers, or use select() to determine which filehandles are ready for I/O. The latter strategy presents a problem, however, because a socket or other filehandle may still block on syswrite() if you attempt to write more data than it is ready to accept. At this point the write attempt blocks and the program stalls. To avoid this, you may use nonblocking I/O. This chapter describes how to set up and use nonblocking I/O. In addition to avoiding blocking during reads and writes , nonblocking I/O can also be used to avoid long waits during the connect() call. As we will see, nonblocking I/O avoids the problems associated with managing threads and processes but introduces its own complexities. |