Skip to content Skip to sidebar Skip to footer

How To Kill Subprocess If No Activity In Stdout/stderr

I am running a program from a python script (currently with os.system). However, sometimes the program hangs at a point and I would like to kill it if nothing is written to stdout

Solution 1:

Try using signal.alarm to set a timer after each line is received, and then handle SIGALRM by checking if too much time has passed since the last line.


Solution 2:

For completeness, here's the code I ended up using, making use of the suggested signal.alarm:

import time
import shlex
import subprocess

logfile = open(log, 'w', 1)
# cmd is command to run
args = shlex.split(cmd)   # tokenise args list
p = subprocess.Popen(args, shell=False, bufsize=0, stdin=None,
                     stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

def _handler(signum, frame):
    print('Timeout of %s min reached, stopping execution' % timeout)
    p.kill()
    time.sleep(30)  # to ensure no ghost process is left running
    raise RuntimeError('Timeout')

signal.signal(signal.SIGALRM, _handler)
try:
    while True:
        signal.alarm(int(timeout))
        inline = p.stdout.readline()
        if not inline:
            break
        logfile.write(inline)
        signal.alarm(0)
except RuntimeError:
    logfile.close()
    return 0

p.communicate()   # wait for process to finish, get return code
logfile.close()
return p.returncode

Post a Comment for "How To Kill Subprocess If No Activity In Stdout/stderr"