Skip to content

Instantly share code, notes, and snippets.

@righthandabacus
Created January 2, 2019 04:04
Show Gist options
  • Save righthandabacus/ae7e85b5d3216eb45990753b1ab380e9 to your computer and use it in GitHub Desktop.
Save righthandabacus/ae7e85b5d3216eb45990753b1ab380e9 to your computer and use it in GitHub Desktop.
Exit signal - work around the lack of UNIX signal in Windows
import atexit
import time
import logging
import signal
import os
def sighandler(sigcode, x):
print("Signal Exit!!", flush=True)
print([sigcode, x], flush=True)
exitcall()
os._exit(0)
def exitcall():
print("Exit!!", flush=True)
with open("a.txt", "w") as fp:
fp.write("1")
logging.warning("exit!")
def main():
atexit.register(exitcall)
termsigs = [getattr(signal, s) for s in dir(signal) if s in ["SIGABRT", "SIGINT", "SIGTERM", "SIGBREAK"]]
print(dir(signal), flush=True)
print(termsigs, flush=True)
for sig in termsigs:
signal.signal(sig, sighandler)
while True:
time.sleep(1)
logging.warning("main end")
if __name__ == "__main__":
try:
main()
finally:
print("finally", flush=True)
exitcall()
# The above is is test out the atexit mechanism as to write a daemon program
# See: https://github.com/msys2/msys2/wiki/Porting#signals-in-mintty
# Running Win CPython inside mintty interactively means the Ctrl-C signal
# is not sent to the program but intercepted by the terminal and ask the
# terminal to terminate the process abruptly. Cygwin CPython works as expected.
#
# Windows has SIGBREAK but Ctrl-C is SIGINT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment