问题
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