Is it possible to identify in the python application type of external exit/break? I would like to do different actions (release sources slow & correct/complex or fast & partly/dirty) based on different external exit reasons e.g. 'shutdown', 'restart', 'kill', 'kill -x'?
I used simple code with atexit, but it is without ability to identify the reason/urgency (it is not useful for me). See sample code:
import atexit
def OnCorrectExit(user):
print(user, "Release sources and exit Python application")
atexit.register(OnCorrectExit)
or version with decorator
import atexit
@atexit.register
def OnCorrectExit(user):
print(user, "Release sources and exit Python application")
Do you know, how to identify different exit urgency in python and based on that build different type of resource cleaning?
I have the answer. It is possible easy catch exit state based on Signals processing (documentation see), sample of code:
import signal
def OnCorrectExit(signalNumber, frame):
print('SignalNumber:', signalNumber)
return
if __name__ == '__main__':
# Set the signal handler
signal.signal(signal.SIGHUP, OnCorrectExit)
signal.signal(signal.SIGINT, OnCorrectExit)
signal.signal(signal.SIGQUIT, OnCorrectExit)
signal.signal(signal.SIGILL, OnCorrectExit)
signal.signal(signal.SIGTRAP, OnCorrectExit)
signal.signal(signal.SIGABRT, OnCorrectExit)
signal.signal(signal.SIGBUS, OnCorrectExit)
signal.signal(signal.SIGFPE, OnCorrectExit)
#signal.signal(signal.SIGKILL, OnCorrectExit)
signal.signal(signal.SIGUSR1, OnCorrectExit)
signal.signal(signal.SIGSEGV, OnCorrectExit)
signal.signal(signal.SIGUSR2, OnCorrectExit)
signal.signal(signal.SIGPIPE, OnCorrectExit)
signal.signal(signal.SIGALRM, OnCorrectExit)
signal.signal(signal.SIGTERM, OnCorrectExit)