How to terminate a process with a ZeroMQ socket that has been closed?
node.js, zeromq
Solution
Given the default ZeroMQ API specifications, any attempts to `.close()` a socket instance is blocking until a certain amount of time expires.
Typical graceful termination sequence relies on a practice of pre-setting this instance attribute right upon its creation:
socket.setsockopt( zmq.LINGER, 0 ); // A SYSTEMATIC STEP UPON CREATION
`ZMQ_LINGER`: Set linger period for socket shutdown The `ZMQ_LINGER` option shall set the linger period for the specified socket. The linger period determines how long pending messages which have yet to be sent to a peer shall linger in memory after a socket is disconnected with `zmq_disconnect()` or closed with `zmq_close()`, and further affects the termination of the socket's context with `zmq_ctx_term()`. The following outlines the different behaviours: - A value of -1 specifies an infinite linger period. Pending messages shall not be discarded after a call to `zmq_disconnect()` or `zmq_close()`; attempting to terminate the socket's context with `zmq_ctx_term()` shall block until all pending messages have been sent to a peer. - The value of 0 specifies no linger period. Pending messages shall be discarded immediately after a call to `zmq_disconnect()` or `zmq_close()`. - Positive values specify an upper bound for the linger period in milliseconds. Pending messages shall not be discarded after a call to `zmq_disconnect()` or `zmq_close()`; attempting to terminate the socket's context with `zmq_ctx_term()` shall block until either all pending messages have been sent to a peer, or the linger period expires, after which any pending messages shall be discarded. Default value ~ 30000 [ms] ( for all socket types )
For respective details, kindly read the ZeroMQ API documentation.
Problem
I'm making a publish subscribe using ZeroMQ. Here is a simplified code : ``` import zmq from 'zeromq'; import d from 'debug'; const debug = d('publisher'); let port = '8000'; let subject = 'FLIGHTS'; const socket = zmq.socket('pub'); socket.on('close', function(...toto) { debug('connection closed'); }); socket.on('close_error', function(...toto) { debug('error while closing connexion'); }); socket.monitor(10, 0); socket.bindSync('tcp://*:' + port); export function send(message: object) { const jsonMessage = JSON.stringify(message); socket.send([subject, jsonMessage]); } export function close() { socket.close(); } setTimeout( () => close(), 3000 ); ``` The problem I have is that the process won't exit even if the socket is closed after 3 seconds. I can't use `process.exit` because the module I'm making is used in a lot a jest tests. I didn't find anything in the ZeroMQ documentation.