Some applications require sockets that do not block. For example, a server would return an error code, not executing a request that cannot complete immediately. This error could cause the process to be suspended, awaiting completion. After creating and connecting a socket, issuing a fcntl(2) call, as shown in the following example, makes the socket nonblocking.
#include <fcntl.h> #include <sys/file.h> ... int fileflags; int s; ... s = socket(AF_INET6, SOCK_STREAM, 0); ... if (fileflags = fcntl(s, F_GETFL, 0) == -1) perror("fcntl F_GETFL"); exit(1); } if (fcntl(s, F_SETFL, fileflags | FNDELAY) == -1) perror("fcntl F_SETFL, FNDELAY"); exit(1); }
When performing I/O on a nonblocking socket, check for the error EWOULDBLOCK in errno.h, which occurs when an operation would normally block. accept(3SOCKET), connect(3SOCKET), send(3SOCKET), recv(3SOCKET), read(2), and write(2) can all return EWOULDBLOCK. If an operation such as a send(3SOCKET) cannot be done in its entirety but partial writes work, as when using a stream socket, all available data is processed. The return value is the amount of data actually sent.