Nonblocking Sockets
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.
Example 7-11 Setting a Nonblocking Socket
#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
(),
connect
(), send
(), recv
(), read
(), and write
()
can all return
EWOULDBLOCK
. If an operation such as a
send
()
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. For more information, see the
accept
(3C),
connect
(3C),
send
(3C),
read
(2),
write
(2), and
recv
(3C) man pages.