Python break from socket receive on SIGINT

橙三吉。 提交于 2020-01-04 09:40:08

问题


I'm working on a program that receives data from a socket, and when a signal is sent, I want to be able to break from the receive.

What I have now:

class Killer: 
    die = False
    def __init__(self):
        signal.signal(signal.SIGINT, self.terminate)
        signal.signal(signal.SIGTERM, self.terminate)

    def terminate(self, signum, frame):
        print ("caught " + str(signum))
        self.die = True;

sock = socket.socket()
# Generic socket setup

while (~killer.die):
    #generic data setup
    sock.receive(data)

sock.shutdown(socket.SHUT_RDWR)

When the interrupt is caught, it prints and then goes back into waiting.

Is there a way to break from the receive on receiving a signal?


回答1:


Since Python 3.5, interrupted system calls are automatically resumed after invoking the (Python) signal handler. If you don’t want that, raise an exception in your handler.



来源:https://stackoverflow.com/questions/49417041/python-break-from-socket-receive-on-sigint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!