From 8b7ac4c2a9c3ede95d6f5f9717a1939a23788964 Mon Sep 17 00:00:00 2001 From: Martin Sustrik Date: Fri, 2 Sep 2011 15:34:12 +0200 Subject: Close file descriptors on exec (issue 218) When exec is executed to start a different process image old 0MQ file descriptors could stay open, thus blocking TCP ports and alike. This patch should solve the problem. Signed-off-by: Martin Sustrik --- src/ip.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'src/ip.cpp') diff --git a/src/ip.cpp b/src/ip.cpp index e1f0e6b..b11a244 100644 --- a/src/ip.cpp +++ b/src/ip.cpp @@ -36,6 +36,29 @@ #include #endif +zmq::fd_t zmq::open_socket (int domain_, int type_, int protocol_) +{ + // Setting this option result in sane behaviour when exec() functions + // are used. Old sockets are closed and don't block TCP ports etc. +#if defined SOCK_CLOEXEC + type_ |= SOCK_CLOEXEC; +#endif + + fd_t s = socket (domain_, type_, protocol_); + if (s == retired_fd) + return retired_fd; + + // If there's no SOCK_CLOEXEC, let's try the second best option. Note that + // race condition can cause socket not to be closed (if fork happens + // between socket creation and this point). +#if !defined SOCK_CLOEXEC && defined FD_CLOEXEC + int rc = fcntl (s, F_SETFD, FD_CLOEXEC); + errno_assert (rc != -1); +#endif + + return s; +} + void zmq::tune_tcp_socket (fd_t s_) { // Disable Nagle's algorithm. We are doing data batching on 0MQ level, -- cgit v1.2.3