Python script does not terminate after timeout in ZMQ recv ()
This is my first experience with IPC and I wrote this script:
#!/usr/bin/python
import zmq
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.setsockopt(zmq.RCVTIMEO, 2000)
socket.connect ("ipc:///tmp/something")
socket.send(b"123")
try:
message = socket.recv()
except:
print("DEBUG!")
message = None
When my server script is running (it just sends the response) everything works fine.
But when the tags are inactive (for example, due to the absence of a server), the script will not terminate after "DEBUG!" - print and I need to manually stop it using + . .recv()
CtrlC
I tried to disable and close the socket, but it doesn't change anything.
When I put my entire script in a function and call it I get the following error on KeyboardInterrupt:
^CException ignored in: <bound method Context.__del__ of <zmq.sugar.context.Context object at 0x7f16a36d5128>>
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/zmq/sugar/context.py", line 46, in __del__
self.term()
File "zmq/backend/cython/context.pyx", line 136, in zmq.backend.cython.context.Context.term (zmq/backend/cython/context.c:2339)
File "zmq/backend/cython/checkrc.pxd", line 12, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/context.c:3207)
KeyboardInterrupt
I am running Python 3.6.1 and version 16.0.2 of the PyZMQ module on Arch Linux.
source to share
Can take this as a standard ZeroMQ infrastructure configuration policy:
The default value of the attribute makes the instance wait while trying . Therefore, set this value to avoid this function / behavior immediately after instantiation, rather than permanently hanging on completion. LINGER
socket
.close()
0
import zmq
nIOthreads = 2 # ____POLICY: set 2+: { 0: non-blocking, 1: blocking, 2: ..., }
context = zmq.Context( nIOthreads ) # ____POLICY: set several IO-datapumps
socket = context.socket( zmq.PAIR )
socket.setsockopt( zmq.LINGER, 0 ) # ____POLICY: set upon instantiations
socket.setsockopt( zmq.AFFINITY, 1 ) # ____POLICY: map upon IO-type thread
socket.setsockopt( zmq.RCVTIMEO, 2000 )
socket.connect( "ipc:///tmp/something" )
socket.send( b"123" )
try:
message = socket.recv()
except:
print( "DEBUG!" )
message = None
finally:
socket.close() # ____POLICY: graceful termination
context.term() # ____POLICY: graceful termination
source to share
user3666197's answer is correct in the sense that it socket.setsockopt(zmq.LINGER, 0)
will solve the problem you described.
But for the docs, the PAIR socket is only intended to be used for inter-thread communication in a single process. In particular, it will not reconnect the connection.
It may work correctly via ipc (I've never tried it), but I recommend using a different socket type.
source to share