python脚本在ZMQ recv()中超时后未终止

到目前为止,这是我第一次使用IPC,并且编写了以下脚本:

#!/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

当我的服务器脚本运行时(它只是发送一个答案),一切工作正常.

但是,当.recv()调用超时(例如,因为没有服务器在运行)时,脚本在“ DEBUG!”打印后不会终止,我必须使用Ctrl C手动将其停止.

我尝试断开并关闭套接字,但是它没有任何改变.

当我将整个脚本放入函数中并调用它时,我在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

我在Arch Linux上运行Python 3.6.1和PyZMQ模块的16.0.2版本.

解决方法:

可以将其作为标准的ZeroMQ基础结构设置策略:

LINGER属性的默认值强制套接字实例等待尝试.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
上一篇:python-如何在具有多个IP的计算机上控制ZeroMQ数据包的源IP地址?


下一篇:POJ-2251 Dungeon Master