24
loading...
This website collects cookies to deliver better user experience
import signal # (1)
import time
import os
should_quit = False # (2)
def main():
stop_signal = signal.SIGUSR1 # (3)
signal.signal(stop_signal, on_signal) # (4)
print(f"Starting - process id is: {os.getpid()}") # (5)
print(f"Send {stop_signal} to safely stop") # (6)
while not should_quit:
print("Doing work, please do not interrupt this.")
time.sleep(3) # (7)
print("Done with this unit of work")
print("Stopping")
def on_signal(signum, frame): # (8)
global should_quit
print("Received request to stop...doing so when it is safe.")
should_quit = True # (9)
if __name__ == "__main__":
main()
should_quit
) to keep track of when the program should stop.SIGUSR1
for this example. There are many different signals,
some are reserved for special purposes by your OS or programming language.
SIGUSR1
is set aside for programmers to define their own custom handler.SIGUSR1
, I want you to call the on_signal
handler.SIGUSR1
maps to 10
.signum
and frame
.on_signal
simply sets should_quit
to True
, the next time we check against it, the programs stops.$ python program.py
Starting - process id is: 25716
Send 10 to safely stop
Doing work, please do not interrupt this.
Done with this unit of work
Doing work, please do not interrupt this.
Done with this unit of work
Doing work, please do not interrupt this.
Done with this unit of work
Doing work, please do not interrupt this.
25716
and the signal is 10
. So to send our signal$ kill -10 25716
Received request to stop...doing so when it is safe.
Done with this unit of work
Stopping