Skip to content

Instantly share code, notes, and snippets.

@liviaerxin
Last active March 8, 2023 06:49
Show Gist options
  • Save liviaerxin/bd246c71959c6460fc00fef33c0a68a3 to your computer and use it in GitHub Desktop.
Save liviaerxin/bd246c71959c6460fc00fef33c0a68a3 to your computer and use it in GitHub Desktop.
Gracefully Kill #python

Gracefully Kill Process

Unix/Linux

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 :)")

Windows

dotnet core gracefully shutdown process

Kill child process when parent was killed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment