2

Ahoy! I have a python wrapper that collects some command line options, embed a subset of them in a file, and calls a subprocess by passing the file name as input and the remaining command line options as options. Then it processes the output and prints it out in a different format. The subprocess is called like this:

# generate cfg file
cfg_file = open(cfg_file_name, "w")
...

# call executable
command = "./%s -time %s -model %s" % (executable, args.time, args.model)
if args.branching != None:
    command += " -branching %s" % args.branching
command += " %s" % (cfg_file_name)

output = run_and_report(command)

# process output
...

Where run_and_report is defined as:

def run_and_report(cmd):

    """Run command on the shell, report stdout, stderr"""
    proc = run(cmd)
    proc.wait()
    output = "".join(map(lambda x: x.rstrip(), proc.stdout))
    return output

and run as

def run(cmd):
    """Open process"""
    return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=True)

The wrapper itself is called in a similar fashion by a higher level procedure that, every now and then, needs to kill some of the wrapper processes it has spawn. My problem is that sometimes killing the wrapper seems to leave the executable running, so the wrapper is effectively killed, but the underlying process is not. However, as far as I know it is not possible to catch a SIGKILL in python as you do with other interrupts so, does anyone know a way to ensure the underlying process is killed?

Thanks,
Tunnuz

tunnuz
  • 23,338
  • 31
  • 90
  • 128
  • 1
    SIGKILL cannot be handled by user space code. – bestsss Apr 16 '13 at 09:19
  • Yet, is there a way to ensure that the underlying process is killed? – tunnuz Apr 16 '13 at 09:22
  • You can have a look at: http://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits Honestly I do not know POSIX way either, beside cron task watchdog – bestsss Apr 16 '13 at 09:50
  • 1
    btw, I thought I had asked: why do you use SIGKILL at all. It should be used only as last resort and the one uses it shall take care of any other process needing termination. SIGTERM or SIGINT is probably what you need to handle. – bestsss Apr 16 '13 at 13:12
  • I will probably review my code to use SIGTERM instead. – tunnuz Apr 16 '13 at 13:41
  • Possible duplicate of [how to handle os.system sigkill signal inside python?](https://stackoverflow.com/questions/33242630/how-to-handle-os-system-sigkill-signal-inside-python) – gmauch Mar 27 '19 at 19:44

0 Answers0