I have a piece of Python code as below:
import sys
import signal
import atexit
def release():
print "Release resources..."
def sigHandler(signo, frame):
release()
sys.exit(0)
if __name__ == "__main__":
signal.signal(signal.SIGTERM, sigHandler)
atexit.register(release)
while True:
pass
The real code is far more complex than this snippets, but the structures are the same: i.e. main function maintains an infinite loop.
I need a signal callback to release the resources occupied, like DB handle.
Then I add a SIGTERM
handler, in case the server is killed, which simply invoke the release function and then exit the process.
The atexit
one aims to handling process complete successfully.
Now I have a problem I just want release
to be invoked only once when the process is killed. Any improvement on my code?
main
? – Fimbria