7

When I run the following code, I get an error on the first call to zmq_poll (i.e. it returns -1). The zmq_errno() returns 128 and the zmr_strerror(128) call returns "Unknown error". I have been using ZMQ with C++ for a while now without any problems, but I can't get a call to zmq_poll to work, no matter how simple it is.

Calling zmq::version reveals that I am using ZMQ version 2.1.10.

Does anyone have an idea as to why zmq_poll is failing?

#include <zmq/zmq.hpp>

int main(int argc, char* argv[])
{
    zmq::context_t context(1);
    zmq::socket_t repA(context, ZMQ_REP);
    zmq::socket_t repB(context, ZMQ_REP);
    repA.bind("tcp://127.0.0.1:5555");
    repB.bind("tcp://127.0.0.1:5556");
    zmq::pollitem_t items[] =
    {
        { &repA, 0, ZMQ_POLLIN, 0 },
        { &repB, 0, ZMQ_POLLIN, 0 }
    };
    while (true)
    {
        int rc = zmq_poll(items, 2, 1000);
        if (rc < 0)
        {
            int code = zmq_errno(); //code = 128
            auto message = zmq_strerror(code); //message = "Unknown error"
        }
    }
}
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
  • 1
    What's the value of errno? _Upon failure, zmq_poll() shall return -1 and set errno to one of the values defined below._ http://api.zeromq.org/2-1:zmq-poll – flup May 07 '13 at 23:03
  • @flup I now see that `zmq_poll` doesn't directly return the error number (it just signals with `-1`) and that you have to call `zmq_errno()` to actually get the real error number. Having done this, I get the error number `128`. (Updated question) – Timothy Shields May 07 '13 at 23:08
  • 1
    _To obtain a ØMQ socket for use in a zmq_pollitem_t structure, you should cast an instance of the socket_t class to (void *)_. So I suspect you should cast `repA` instead of sending its address. – flup May 07 '13 at 23:17
  • @flup Thanks, that did it. Sure enough, there is an overloaded cast to `void*` on the `zmq::socket_t` class. Go ahead and just make an answer with that correction and I'll mark it as the answer. – Timothy Shields May 07 '13 at 23:27

1 Answers1

9

To obtain a ØMQ socket for use in a zmq_pollitem_t structure, you should cast an instance of the socket_t class to (void *).

So it should be

zmq::pollitem_t items[] =
{
    { repA, 0, ZMQ_POLLIN, 0 },
    { repB, 0, ZMQ_POLLIN, 0 }
};

Without the &.

flup
  • 26,937
  • 7
  • 52
  • 74
  • 1
    Just to clarify this very old (but correct) answer, `zmq::socket_t` is a C++ wrapper around the ZMQ socket (which is a `void*` (see [zmq_socket](http://api.zeromq.org/4-2:zmq_socket) )). `zmq::socket_t` defines `operator void*()` so that it can naturally be used as above. – jwm Dec 06 '18 at 19:14
  • 1
    I think this breaks down in modern versions of C++, i had to apply a manual, old-style cast to void* to make it compile under c++17. – Rich Henry Jan 15 '19 at 15:12