The Linux Programming Interface

(nextflipdebug5) #1
Sockets: Advanced Topics 1281

Listing 61-4: Setting the SO_REUSEADDR socket option

int sockfd, optval;

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
errExit("socket");

optval = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval,
sizeof(optval)) == -1)
errExit("socket");

if (bind(sockfd, &addr, addrlen) == -1)
errExit("bind");
if (listen(sockfd, backlog) == -1)
errExit("listen");

61.11 Inheritance of Flags and Options Across accept()


Various flags and settings can be associated with open file descriptions and file
descriptors (Section 5.4). Furthermore, as described in Section 61.9, various options
can be set for a socket. If these flags and options are set on a listening socket, are
they inherited by the new socket returned by accept()? We describe the details here.
On Linux, the following attributes are not inherited by the new file descriptor
returned by accept():

z The status flags associated with an open file description—the flags that can be
altered using the fcntl() F_SETFL operation (Section 5.3). These include flags
such as O_NONBLOCK and O_ASYNC.
z The file descriptor flags—the flags that can be altered using the fcntl() F_SETFD
operation. The only such flag is the close-on-exec flag (FD_CLOEXEC, described in
Section 27.4).
z The fcntl() F_SETOWN (owner process ID) and F_SETSIG (generated signal) file
descriptor attributes associated with signal-driven I/O (Section 63.3).

On the other hand, the new descriptor returned by accept() inherits a copy of most
of the socket options that can be set using setsockopt() (Section 61.9).
SUSv3 is silent on the details described here, and the inheritance rules for the
new connected socket returned by accept() vary across UNIX implementations.
Most notably, on some UNIX implementations, if open file status flags such as
O_NONBLOCK and O_ASYNC are set on a listening socket, then they are inherited by the
new socket returned by accept(). For portability, it may be necessary to explicitly
reset these attributes on a socket returned by accept().
Free download pdf