Duplicate of How to prevent a block of code from being interrupted by KeyboardInterrupt in Python?
Purpose:
- When program receives a signal, it exits only when it is ready.
Problem:
- Desired behavior:
- Signal arrives during target block. Program exits after target block finishes.
- Signal arrives outside target block. Program exits.
- Current behavior:
- Signal arrives during target block. Program hangs.
- Signal arrives outside target block. Program exits.
Generic implementation of my design:
import threading, signal
def huphandler(signum, frame):
with sig_lock:
os._exit(0)
def loop():
print 'in lock'
time.sleep(5)
def idle_loop():
while True:
with sig_lock:
t = multiprocessing.Process(target=loop)
t.start()
t.join()
print 'out lock'
time.sleep(5)
sig_lock = threading.Lock()
signal.signal(signal.SIGHUP, huphandler)
idle_loop()