Socket I/O Modes

Sockets can be set to either blocking or nonblocking I/O mode.

The FIONBIO ioctl operation is used to determine this mode. When the FIONBIO ioctl is set, the socket is marked nonblocking. If a read is tried and the desired data is not available, the socket does not wait for the data to become available, but returns immediately with the EWOULDBLOCK error code.

Note: The EWOULDBLOCK error code is defined with the _BSD define and is equivalent to the EAGAIN error code.

When the FIONBIO ioctl is not set, the socket is in blocking mode. In this mode, if a read is tried and the desired data is not available, the calling process waits for the data. Similarly, when writing, if FIONBIO is set and the output queue is full, an attempt to write causes the process to return immediately with an error code of EWOULDBLOCK.

When performing nonblocking I/O on sockets, a program must check for the EWOULDBLOCK error code (stored in the errno global variable). This occurs when an operation would normally block, but the socket it was performed on is marked as nonblocking. The following socket subroutines return a EWOULDBLOCK error code:

Processes using these subroutines should be prepared to deal with the EWOULDBLOCK error code. For a nonblocking socket, the connect subroutine returns an EINPROGRESS error code.

If an operation such as a send operation cannot be done completely, but partial writes are permissible (for example when using a stream socket), the data that can be sent immediately is processed, and the return value indicates the amount actually sent.