Welcome, guest | Sign In | My Account | Store | Cart

atexit handlers are not called when a process is killed, this recipe show how to fix that.

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/usr/bin/env python

from signal import signal, SIGTERM
from sys import exit
import atexit

def cleanup():
    print "Cleanup"

if __name__ == "__main__":
    from time import sleep
    atexit.register(cleanup)

    # Normal exit when killed
    signal(SIGTERM, lambda signum, stack_frame: exit(1))

    sleep(10)

You might want to catch other signals (like SIGINT which in Python translates to KeyboardInterrupt).

Please note that it's very bad idea to mix threads and signals :)