Making a Clean Exit
Classy programmers share the same motto as classy hit men: always clean up when you finish the job. When you use ØMQ in a language like Python, stuff gets automatically freed for you. But when using C, you have to carefully free objects when you’re finished with them, or else you get memory leaks, unstable applications, and generally bad karma.
Memory leaks are one thing, but ØMQ is quite finicky about how you
exit an application. The reasons are technical and painful, but the
upshot is that if you leave any sockets open, the zmq_ctx_destroy() function will hang forever.
And even if you close all sockets, zmq_ctx_destroy() will by default wait forever
if there are pending connects or sends, unless you set the LINGER to zero
on those sockets before closing them.
The ØMQ objects we need to worry about are messages, sockets, and contexts. Luckily, it’s quite simple, at least in simple programs:
Always close a message the moment you are done with it, using
zmq_msg_close().If you are opening and closing a lot of sockets, that’s probably a sign that you need to redesign your application.
When you exit the program, close your sockets and then call
zmq_ctx_destroy(). This destroys the context.
This is at least the case for C development. In a language with automatic object destruction, sockets and contexts will be destroyed as you leave the scope. If you use exceptions you’ll have to do the cleanup in something like a “final” block, the same as for any resource.
If you’re ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access