Advertisement
furas

Python - catching "kill" signal, sending "kill" signal

May 23rd, 2018
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. ############################################################################
  2. # script.py
  3. # It has signal's handler so it can close connections/files at the end.
  4. # It saves its PID in file so admin can use it to send signal to this script
  5. ############################################################################
  6.  
  7. import signal
  8. import time
  9. import os
  10.  
  11. def exit_gracefully(signum, frame):
  12.     print("closing connections/files ...")
  13.    
  14.     # closing ... longer time
  15.     time.sleep(3)
  16.    
  17.     print("end of the program.")
  18.     exit()
  19.     #exit(1) # exit with some code
  20.  
  21. #---------------------------------------------------------------------------
  22.    
  23. # register signals    
  24. signal.signal(signal.SIGINT, exit_gracefully)
  25. signal.signal(signal.SIGTERM, exit_gracefully)
  26.  
  27. # save PID in file so admin can use it to kill this script
  28. pid = os.getpid()
  29. with open('script.lock', 'w') as out:
  30.     out.write(str(pid))
  31.  
  32. # long runnig program
  33. while True:
  34.     print("simulate long running program ...")
  35.     time.sleep(1)
  36.  
  37. ############################################################################
  38. # admin.py
  39. # It gets script's PID from file and sends signal to close this script
  40. ############################################################################
  41.  
  42. import signal
  43. import os
  44.  
  45. with open('script.lock') as f:
  46.     pid = int(f.read())
  47. os.kill(pid, signal.SIGTERM)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement