Avoid race condition with accept4 where available

Linux provides accept4(2) which will return a socket with FD_CLOEXEC set
when called with the SOCK_CLOEXEC flag. So call this when available and
fall back to fcntl(..., FD_CLOEXEC) if not.
This commit is contained in:
Peter J. Holzer
2016-07-30 21:22:50 +02:00
parent 5e684172d6
commit e175fe21e5
2 changed files with 10 additions and 2 deletions

View File

@@ -273,7 +273,11 @@ zmq::fd_t zmq::tcp_listener_t::accept ()
#else
socklen_t ss_len = sizeof (ss);
#endif
#if defined ZMQ_HAVE_SOCK_CLOEXEC
fd_t sock = ::accept4 (s, (struct sockaddr *) &ss, &ss_len, SOCK_CLOEXEC);
#else
fd_t sock = ::accept (s, (struct sockaddr *) &ss, &ss_len);
#endif
#ifdef ZMQ_HAVE_WINDOWS
if (sock == INVALID_SOCKET) {
@@ -299,9 +303,9 @@ zmq::fd_t zmq::tcp_listener_t::accept ()
}
#endif
#if !defined ZMQ_HAVE_SOCK_CLOEXEC && defined FD_CLOEXEC
// Race condition can cause socket not to be closed (if fork happens
// between accept and this point).
#ifdef FD_CLOEXEC
int rc = fcntl (sock, F_SETFD, FD_CLOEXEC);
errno_assert (rc != -1);
#endif