pynng icon indicating copy to clipboard operation
pynng copied to clipboard

pynng sock.recv() not interruptable

Open Sec42 opened this issue 2 years ago • 4 comments

If I call .recv() on a socket created without recv_timeout, the call isn't interruptable with ^C.

Example:

with pynng.Sub0() as sock:
    sock.subscribe("")
    sock.dial(addr)
    msg = sock.recv()

Hangs indefinitely if I press ^C until a messages comes in.

Sec42 avatar May 26 '22 15:05 Sec42

You can work around this by adding a small timeout, inside a while loop, or while checking if some flag for shutdown is up (ex. to stop a thread)

with pynng.Sub0(...) as sock:
    sock.subscribe("")
    sock.dial(addr)
    while True: # or not stop_request
        try:
            msg = sock.recv(timeout=1.0)
        except pynng.exceptions.Timeout:
            pass 

ntakouris avatar Oct 12 '22 07:10 ntakouris

This behavior cannot be fixed without changes to the underlying nng library; see an issue I opened a couple years ago for a discussion.

I'll leave this issue open just as a reference.

codypiersall avatar Nov 27 '22 18:11 codypiersall

I have tried your solution @ntakouris and it works, thank you. However, I had to abandon it because try-except statements in Python are very cheap (performance-wise) if there is no exception, but become expensive when the exception occurs. Since I had several IPC channels working together, I was adding a big performance burden on my code.

aqc-carlodri avatar Dec 06 '22 07:12 aqc-carlodri

I was playing around with pyzmq and stumbled into the same issue, and I found this SO reply that actually worked. Just sharing for now, haven't tried it with pynng. Will post back if it works.

aqc-carlodri avatar Jan 12 '23 13:01 aqc-carlodri