How to Handle Os.System Sigkill Signal Inside Python

Multiprocessing Process os.system('kill -9 {0}'.format(pid)) fails on Linux

Make sure you're running on Linux. Also consider using os.kill(pid, signal.SIGKILL).

Not exactly what you're asking, but consider switching to psutil for cross-platform goodness as well as conveniences such as wait_procs which will gracefully send SIGTERM, wait, then send SIGKILL.

signal.SIGKILL should be available on Linux (not on Windows).

The multiprocessing module recently gained a kill() method that falls back to terminate on Windows.

How to process SIGTERM signal gracefully?

A class based clean to use solution:

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, *args):
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 :)")

Python parent process is not catching SIGTERM/SIGINT signals when launching subprocess using os.sytem()

I think you'll have better luck with subprocess than os.system. In particular, I think you'll want to use subprocess with shell=False so that your child command is executed without a subshell (which might interfere with your ability to handle these kinds of signal-handling scenarios).

The code below does what you want, if I understand you correctly: CTRL-C causes both child and parent to stop; but if child dies for some other reason, parent will run the child again.

Here's a parent program similar to yours:

import signal
import subprocess

shutdown = False

def sigterm_handler(signum, frame):
print 'parent got shutdown'
global shutdown
shutdown = True

if __name__ == '__main__':
signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigterm_handler)
cmd_args = ['python', 'child.py']
while not shutdown:
print 'executing', cmd_args
try:
subprocess.check_call(cmd_args)
except subprocess.CalledProcessError:
print 'child died'
pass
print 'Exiting Parent'

And here is a child program that runs for a while and then dies with a ZeroDivisionError.

import signal
import sys
import time

def sigterm_handler(signum, frame):
print 'child got shutdown'
sys.exit(0)

if __name__ == '__main__':
signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigterm_handler)
for i in range(3, -1, -1):
print 'Child Process Running', i, i/i
time.sleep(3)


Related Topics



Leave a reply



Submit