[zeromq-dev] Short-lived processes

Randall Nortman rnzmq at wonderclown.net
Tue Jan 28 18:23:35 CET 2014

I need to send zeromq messages from very short-lived processes, and
I'm wondering how best to go about it.  When I say short-lived, I mean
on the order of 10-20ms (with all messages going to either localhost
or over a fast LAN, so this is feasible at least in principle).  I am
using PUB/SUB, and the SUB is bound by a long-lived daemon process
(PUB connects to SUB).  If I send a message immediately after
zmq_connect, the message goes nowhere (and I understand the reasons
for this).  So I need to wait (but not more than a few ms) for the zmq
background thread to get up and running and establish the connection.

Two ways of doing this pop into mind.  First is to poll my PUB socket
and wait until it is sendable (ZMQ_POLLOUT).  But I think that will
not work, because PUB sockets never block, so it will return
immediately and then the message I send will be dropped (right?).

The other obvious way is to open a monitor socket and wait for
ZMQ_EVENT_CONNECTED.  I suppose the correct ordering of operations to
ensure that I don't miss the CONNECTED event would be:

       ctx = zmq_context();
       pub = zmq_socket(ctx, ZMQ_PUB);
       zmq_socket_monitor(pub, "inproc://foo", events);
       mon = zmq_socket(ctx, ZMQ_PAIR);
       zmq_connect(mon, "inproc://foo");
       zmq_connect(pub, "tcp://localhost:1234");

       // Now start listening on mon (with short timeout).  Once
       // connected:

       zmq_send(pub, ...);
       zmq_setsockopt(pub, ZMQ_LINGER, ...) // 10ms;

       // With the understanding that there are still no guarantees
       // that anybody heard me, but in normal operations, if things
       // are not fubar, it will probably work.

Is that the most lightweight way to do this?  Is there something
better?  Maybe I should just have the daemon also open up a PULL
socket, and then I can simplify short-lived clients?  In that case,
I'd create and connect a PUSH, wait 10ms for POLLOUT, send my message,
set linger to 10ms, and then zmq_close as above.  Would that work just
as well?  (At the expense of complicating the daemon process by having
two sockets that it listens on...)

More information about the zeromq-dev mailing list