When linux shuts down, all processes receive SIGTERM, and if they do not stop after some timeout, they will be killed with SIGKILL. You can implement a signal handler for the correct shutdown of your application using the module signal. systemd(unlike upstartin previous versions of Ubuntu) additionally sends SIGHUPat shutdown.
To verify that this really works, I tried the following script on two Ubuntu virtual machines (12.04 and 16.04). The system waits 10 seconds (12.04 / upstart) or 90s (16.04 / systemd) before issuing SIGKILL.
the script ignores SIGHUP(which otherwise would also destroy the process unholy) and will continuously print the time from the moment the signal is received SIGTERMinto a text file.
disown ( bash) .
python signaltest.py &
disown
signaltest.py
import signal
import time
stopped = False
out = open('log.txt', 'w')
def stop(sig, frame):
global stopped
stopped = True
out.write('caught SIGTERM\n')
out.flush()
def ignore(sig, frsma):
out.write('ignoring signal %d\n' % sig)
out.flush()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGHUP, ignore)
while not stopped:
out.write('running\n')
out.flush()
time.sleep(1)
stop_time = time.time()
while True:
out.write('%.4fs after stop\n' % (time.time() - stop_time))
out.flush()
time.sleep(0.1)
, log.txt, :
10.1990s after stop
12.04
90.2448s after stop
16.04.