On Unix or Linux, it's easy to gracefully kill a application by sending it the SIGTERM
signal. If its process ID is 1234, you can simply run kill 1234
or kill -s TERM 1234
or kill -15 1234
.
Inside target-killed application, you receive the SIGTERM
signal, clean up(such as data backup,...etc) and exit.
A simple python solution,
# https://stackoverflow.com/questions/18499497/how-to-process-sigterm-signal-gracefully
import signal
import time
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
self.kill_now = True
if __name__ == '__main__':
killer = GracefulKiller()
while not killer.kill_now:
time.sleep(1)
print("doing something in a loop ...")
print("End of the program. I was killed gracefully :)")
dotnet core gracefully shutdown process