signaler.cpp 11.8 KB
Newer Older
1
/*
2
    Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file
3

4
    This file is part of libzmq, the ZeroMQ core engine in C++.
5

6 7 8
    libzmq is free software; you can redistribute it and/or modify it under
    the terms of the GNU Lesser General Public License (LGPL) as published
    by the Free Software Foundation; either version 3 of the License, or
9 10
    (at your option) any later version.

11 12 13 14 15 16 17 18 19 20 21 22 23 24
    As a special exception, the Contributors give you permission to link
    this library with independent modules to produce an executable,
    regardless of the license terms of these independent modules, and to
    copy and distribute the resulting executable under terms of your choice,
    provided that you also meet, for each linked independent module, the
    terms and conditions of the license of that module. An independent
    module is a module which is not derived from or based on this library.
    If you modify this library, you must extend this exception to your
    version of the library.

    libzmq is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
    License for more details.
25 26 27 28 29 30 31 32 33

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

//  On AIX, poll.h has to be included before zmq.h to get consistent
//  definition of pollfd structure (AIX uses 'reqevents' and 'retnevents'
//  instead of 'events' and 'revents' and defines macros to map from POSIX-y
//  names to AIX-specific names).
34 35 36 37 38 39 40 41 42
//  zmq.h must be included *after* poll.h for AIX to build properly.
//  precompiled.hpp includes include/zmq.h
#if defined ZMQ_POLL_BASED_ON_POLL && defined ZMQ_HAVE_AIX
#include <poll.h>
#endif

#include "precompiled.hpp"
#include "poller.hpp"

43
#if defined ZMQ_POLL_BASED_ON_POLL
44
#if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_AIX
45
#include <poll.h>
46
#endif
47
#elif defined ZMQ_POLL_BASED_ON_SELECT
48 49 50 51 52 53 54 55
#if defined ZMQ_HAVE_WINDOWS
#elif defined ZMQ_HAVE_HPUX
#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
#elif defined ZMQ_HAVE_OPENVMS
#include <sys/types.h>
#include <sys/time.h>
56 57 58 59 60
#elif defined ZMQ_HAVE_VXWORKS
#include <sys/types.h>
#include <sys/time.h>
#include <sockLib.h>
#include <strings.h>
61 62 63 64 65 66 67
#else
#include <sys/select.h>
#endif
#endif

#include "signaler.hpp"
#include "likely.hpp"
68
#include "stdint.hpp"
69
#include "config.hpp"
70 71 72
#include "err.hpp"
#include "fd.hpp"
#include "ip.hpp"
73
#include "tcp.hpp"
74

75
#if !defined ZMQ_HAVE_WINDOWS
76 77 78 79 80 81
#include <unistd.h>
#include <netinet/tcp.h>
#include <sys/types.h>
#include <sys/socket.h>
#endif

82
#if !defined(ZMQ_HAVE_WINDOWS)
83 84 85 86 87 88 89 90 91 92 93 94
// Helper to sleep for specific number of milliseconds (or until signal)
//
static int sleep_ms (unsigned int ms_)
{
    if (ms_ == 0)
        return 0;
#if defined ZMQ_HAVE_WINDOWS
    Sleep (ms_ > 0 ? ms_ : INFINITE);
    return 0;
#elif defined ZMQ_HAVE_ANDROID
    usleep (ms_ * 1000);
    return 0;
95 96 97 98 99
#elif defined ZMQ_HAVE_VXWORKS
    struct timespec ns_;
    ns_.tv_sec = ms_ / 1000;
    ns_.tv_nsec = ms_ % 1000 * 1000000;
    return nanosleep (&ns_, 0);
100 101 102 103 104 105 106 107 108 109 110 111
#else
    return usleep (ms_ * 1000);
#endif
}

// Helper to wait on close(), for non-blocking sockets, until it completes
// If EAGAIN is received, will sleep briefly (1-100ms) then try again, until
// the overall timeout is reached.
//
static int close_wait_ms (int fd_, unsigned int max_ms_ = 2000)
{
    unsigned int ms_so_far = 0;
112
    unsigned int step_ms = max_ms_ / 10;
113 114 115 116 117
    if (step_ms < 1)
        step_ms = 1;
    if (step_ms > 100)
        step_ms = 100;

118
    int rc = 0; // do not sleep on first attempt
Pieter Hintjens's avatar
Pieter Hintjens committed
119 120
    do {
        if (rc == -1 && errno == EAGAIN) {
121 122 123 124 125 126 127 128 129 130
            sleep_ms (step_ms);
            ms_so_far += step_ms;
        }
        rc = close (fd_);
    } while (ms_so_far < max_ms_ && rc == -1 && errno == EAGAIN);

    return rc;
}
#endif

131 132 133
zmq::signaler_t::signaler_t ()
{
    //  Create the socketpair for signaling.
134 135 136 137
    if (make_fdpair (&r, &w) == 0) {
        unblock_socket (w);
        unblock_socket (r);
    }
138
#ifdef HAVE_FORK
Martin Hurton's avatar
Martin Hurton committed
139
    pid = getpid ();
140
#endif
141 142
}

143 144
// This might get run after some part of construction failed, leaving one or
// both of r and w retired_fd.
145 146
zmq::signaler_t::~signaler_t ()
{
147
#if defined ZMQ_HAVE_EVENTFD
148 149
    if (r == retired_fd)
        return;
150
    int rc = close_wait_ms (r);
151 152
    errno_assert (rc == 0);
#elif defined ZMQ_HAVE_WINDOWS
153
    if (w != retired_fd) {
154
        const struct linger so_linger = {1, 0};
155
        int rc = setsockopt (w, SOL_SOCKET, SO_LINGER,
156
                             (const char *) &so_linger, sizeof so_linger);
157 158 159 160 161
        //  Only check shutdown if WSASTARTUP was previously done
        if (rc == 0 || WSAGetLastError () != WSANOTINITIALISED) {
            wsa_assert (rc != SOCKET_ERROR);
            rc = closesocket (w);
            wsa_assert (rc != SOCKET_ERROR);
162 163
            if (r == retired_fd)
                return;
164 165 166
            rc = closesocket (r);
            wsa_assert (rc != SOCKET_ERROR);
        }
Richard Newton's avatar
Richard Newton committed
167
    }
168
#else
169 170 171 172 173
    if (w != retired_fd) {
        int rc = close_wait_ms (w);
        errno_assert (rc == 0);
    }
    if (r != retired_fd) {
174
        int rc = close_wait_ms (r);
175 176
        errno_assert (rc == 0);
    }
177 178 179
#endif
}

Martin Hurton's avatar
Martin Hurton committed
180
zmq::fd_t zmq::signaler_t::get_fd () const
181 182 183 184 185 186
{
    return r;
}

void zmq::signaler_t::send ()
{
Martin Hurton's avatar
Martin Hurton committed
187 188
#if defined HAVE_FORK
    if (unlikely (pid != getpid ())) {
189 190 191 192
        //printf("Child process %d signaler_t::send returning without sending #1\n", getpid());
        return; // do not send anything in forked child context
    }
#endif
193 194 195 196 197
#if defined ZMQ_HAVE_EVENTFD
    const uint64_t inc = 1;
    ssize_t sz = write (w, &inc, sizeof (inc));
    errno_assert (sz == sizeof (inc));
#elif defined ZMQ_HAVE_WINDOWS
198
    unsigned char dummy = 0;
199
    while (true) {
200
        int nbytes = ::send (w, (char *) &dummy, sizeof (dummy), 0);
201
        wsa_assert (nbytes != SOCKET_ERROR);
202 203 204 205 206
        if (unlikely (nbytes == SOCKET_ERROR))
            continue;
        zmq_assert (nbytes == sizeof (dummy));
        break;
    }
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
#elif defined ZMQ_HAVE_VXWORKS
    unsigned char dummy = 0;
    while (true) {
        ssize_t nbytes = ::send (w, (char *) &dummy, sizeof (dummy), 0);
        if (unlikely (nbytes == -1 && errno == EINTR))
            continue;
#if defined(HAVE_FORK)
        if (unlikely (pid != getpid ())) {
            //printf("Child process %d signaler_t::send returning without sending #2\n", getpid());
            errno = EINTR;
            break;
        }
#endif
        zmq_assert (nbytes == sizeof dummy);
        break;
    }
223 224 225 226 227 228
#else
    unsigned char dummy = 0;
    while (true) {
        ssize_t nbytes = ::send (w, &dummy, sizeof (dummy), 0);
        if (unlikely (nbytes == -1 && errno == EINTR))
            continue;
229
#if defined(HAVE_FORK)
Martin Hurton's avatar
Martin Hurton committed
230
        if (unlikely (pid != getpid ())) {
231 232 233 234 235
            //printf("Child process %d signaler_t::send returning without sending #2\n", getpid());
            errno = EINTR;
            break;
        }
#endif
Martin Hurton's avatar
Martin Hurton committed
236
        zmq_assert (nbytes == sizeof dummy);
237 238 239 240 241 242 243
        break;
    }
#endif
}

int zmq::signaler_t::wait (int timeout_)
{
244
#ifdef HAVE_FORK
Martin Hurton's avatar
Martin Hurton committed
245
    if (unlikely (pid != getpid ())) {
246
        // we have forked and the file descriptor is closed. Emulate an interrupt
247 248 249 250 251 252 253
        // response.
        //printf("Child process %d signaler_t::wait returning simulating interrupt #1\n", getpid());
        errno = EINTR;
        return -1;
    }
#endif

254
#ifdef ZMQ_POLL_BASED_ON_POLL
255 256 257 258 259
    struct pollfd pfd;
    pfd.fd = r;
    pfd.events = POLLIN;
    int rc = poll (&pfd, 1, timeout_);
    if (unlikely (rc < 0)) {
260
        errno_assert (errno == EINTR);
261
        return -1;
262
    } else if (unlikely (rc == 0)) {
263 264 265
        errno = EAGAIN;
        return -1;
    }
266
#ifdef HAVE_FORK
267
    else if (unlikely (pid != getpid ())) {
268
        // we have forked and the file descriptor is closed. Emulate an interrupt
269 270 271 272 273 274
        // response.
        //printf("Child process %d signaler_t::wait returning simulating interrupt #2\n", getpid());
        errno = EINTR;
        return -1;
    }
#endif
275 276 277 278
    zmq_assert (rc == 1);
    zmq_assert (pfd.revents & POLLIN);
    return 0;

279
#elif defined ZMQ_POLL_BASED_ON_SELECT
280 281 282 283 284

    fd_set fds;
    FD_ZERO (&fds);
    FD_SET (r, &fds);
    struct timeval timeout;
285 286 287 288
    if (timeout_ >= 0) {
        timeout.tv_sec = timeout_ / 1000;
        timeout.tv_usec = timeout_ % 1000 * 1000;
    }
289
#ifdef ZMQ_HAVE_WINDOWS
290
    int rc = select (0, &fds, NULL, NULL, timeout_ >= 0 ? &timeout : NULL);
291 292
    wsa_assert (rc != SOCKET_ERROR);
#else
293
    int rc = select (r + 1, &fds, NULL, NULL, timeout_ >= 0 ? &timeout : NULL);
294
    if (unlikely (rc < 0)) {
295
        errno_assert (errno == EINTR);
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        return -1;
    }
#endif
    if (unlikely (rc == 0)) {
        errno = EAGAIN;
        return -1;
    }
    zmq_assert (rc == 1);
    return 0;

#else
#error
#endif
}

void zmq::signaler_t::recv ()
312
{
313
//  Attempt to read a signal.
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
#if defined ZMQ_HAVE_EVENTFD
    uint64_t dummy;
    ssize_t sz = read (r, &dummy, sizeof (dummy));
    errno_assert (sz == sizeof (dummy));

    //  If we accidentally grabbed the next signal(s) along with the current
    //  one, return it back to the eventfd object.
    if (unlikely (dummy > 1)) {
        const uint64_t inc = dummy - 1;
        ssize_t sz2 = write (w, &inc, sizeof (inc));
        errno_assert (sz2 == sizeof (inc));
        return;
    }

    zmq_assert (dummy == 1);
#else
    unsigned char dummy;
#if defined ZMQ_HAVE_WINDOWS
Pieter Hintjens's avatar
Pieter Hintjens committed
332
    int nbytes = ::recv (r, (char *) &dummy, sizeof (dummy), 0);
333
    wsa_assert (nbytes != SOCKET_ERROR);
334 335 336
#elif defined ZMQ_HAVE_VXWORKS
    ssize_t nbytes = ::recv (r, (char *) &dummy, sizeof (dummy), 0);
    errno_assert (nbytes >= 0);
337 338 339 340 341 342 343 344 345 346
#else
    ssize_t nbytes = ::recv (r, &dummy, sizeof (dummy), 0);
    errno_assert (nbytes >= 0);
#endif
    zmq_assert (nbytes == sizeof (dummy));
    zmq_assert (dummy == 0);
#endif
}

int zmq::signaler_t::recv_failable ()
347
{
348
//  Attempt to read a signal.
349 350 351
#if defined ZMQ_HAVE_EVENTFD
    uint64_t dummy;
    ssize_t sz = read (r, &dummy, sizeof (dummy));
352 353
    if (sz == -1) {
        errno_assert (errno == EAGAIN);
354
        return -1;
355
    } else {
356 357 358 359 360 361 362 363
        errno_assert (sz == sizeof (dummy));

        //  If we accidentally grabbed the next signal(s) along with the current
        //  one, return it back to the eventfd object.
        if (unlikely (dummy > 1)) {
            const uint64_t inc = dummy - 1;
            ssize_t sz2 = write (w, &inc, sizeof (inc));
            errno_assert (sz2 == sizeof (inc));
364
            return 0;
365
        }
366

367 368
        zmq_assert (dummy == 1);
    }
369
#else
370
    unsigned char dummy;
Martin Sustrik's avatar
Martin Sustrik committed
371
#if defined ZMQ_HAVE_WINDOWS
Pieter Hintjens's avatar
Pieter Hintjens committed
372
    int nbytes = ::recv (r, (char *) &dummy, sizeof (dummy), 0);
373
    if (nbytes == SOCKET_ERROR) {
374
        const int last_error = WSAGetLastError ();
375 376
        if (last_error == WSAEWOULDBLOCK) {
            errno = EAGAIN;
377
            return -1;
378
        }
379 380
        wsa_assert (last_error == WSAEWOULDBLOCK);
    }
381 382 383 384 385 386 387 388 389 390
#elif defined ZMQ_HAVE_VXWORKS
    ssize_t nbytes = ::recv (r, (char *) &dummy, sizeof (dummy), 0);
    if (nbytes == -1) {
        if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
            errno = EAGAIN;
            return -1;
        }
        errno_assert (errno == EAGAIN || errno == EWOULDBLOCK
                      || errno == EINTR);
    }
391 392
#else
    ssize_t nbytes = ::recv (r, &dummy, sizeof (dummy), 0);
393 394 395 396 397
    if (nbytes == -1) {
        if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
            errno = EAGAIN;
            return -1;
        }
398 399
        errno_assert (errno == EAGAIN || errno == EWOULDBLOCK
                      || errno == EINTR);
400
    }
401 402 403
#endif
    zmq_assert (nbytes == sizeof (dummy));
    zmq_assert (dummy == 0);
404
#endif
405
    return 0;
406 407
}

408 409 410 411 412
bool zmq::signaler_t::valid () const
{
    return w != retired_fd;
}

413
#ifdef HAVE_FORK
Martin Hurton's avatar
Martin Hurton committed
414
void zmq::signaler_t::forked ()
415
{
416 417 418
    //  Close file descriptors created in the parent and create new pair
    close (r);
    close (w);
419
    make_fdpair (&r, &w);
420 421
}
#endif