Skip to content

Instantly share code, notes, and snippets.

@teepark
Created February 20, 2017 21:46
Show Gist options
  • Save teepark/d297b6e6948054dcb5ba2b462e5eb656 to your computer and use it in GitHub Desktop.
Save teepark/d297b6e6948054dcb5ba2b462e5eb656 to your computer and use it in GitHub Desktop.
testing Thread.join from a signal handler
#!/usr/bin/env python
from datetime import datetime
import os
import signal
import sys
import threading
import time
def main(environ, args):
log("starting main")
thread = Pauser(5)
signal.signal(signal.SIGTERM, sighandler(thread))
thread.start()
time.sleep(1)
log("sending TERM signal")
os.kill(os.getpid(), signal.SIGTERM)
log("main beginning 5 second sleep")
time.sleep(5)
log("main finished sleep, exiting")
return 0
_start = datetime.now()
def log(msg):
print("({} elapsed) {}".format(datetime.now() - _start, msg))
def sighandler(thread):
def handler(signum, frame):
log("signal handler invoked for signal {}".format(signum))
thread.join()
log("signal handler successfully joined thread")
return handler
class Pauser(threading.Thread):
def __init__(self, pause_time):
super(Pauser, self).__init__()
self.pause_time = pause_time
def run(self):
log("pauser beginning {} second sleep".format(self.pause_time))
time.sleep(self.pause_time)
log("pauser finished sleep, exiting")
if __name__ == "__main__":
sys.exit(main(os.environ, sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment