Asynchronous Socket I/O
Asynchronous communication between processes is required in applications
that simultaneously handle multiple requests. Asynchronous sockets must be
of the SOCK_STREAM
type. To make a socket asynchronous,
you issue a
fcntl
(2) call,
as shown in the following example.
Example 7-12 Making a Socket Asynchronous
#include <fcntl.h> #include <sys/file.h> ... int fileflags; int s; ... s = socket(AF_INET6, SOCK_STREAM, 0); ... if (fileflags = fcntl(s, F_GETFL ) == -1) { perror("fcntl F_GETFL"); exit(1); } if (fcntl(s, F_SETFL, fileflags | FNDELAY | FASYNC) == -1) { perror("fcntl F_SETFL, FNDELAY | FASYNC"); exit(1); }
After sockets are initialized, connected, and configured as nonblocking and asynchronous,
communication is similar to reading and writing a file asynchronously. Initiate a
data transfer by using send
(), write
(), recv
(), or read
(). For more information, see
the
send
(3C),
write
(2),
recv
(3C), and
read
(2) man pages. A signal-driven I/O routine completes a data
transfer, as described in the next section.