Kill the subprocess chain on KeyboardInterrupt

I had a strange problem that I encountered when I wrote a script to run my local JBoss instance.

My code looks something like this:

with open("/var/run/jboss/jboss.pid", "wb") as f:
    process = subprocess.Popen(["/opt/jboss/bin/standalone.sh", "-b=0.0.0.0"])
    f.write(str(process.pid))

    try:
        process.wait()
    except KeyboardInterrupt:
        process.kill()

It should be pretty simple to understand, write the PID to the file during its launch, as soon as I get it KeyboardInterrupt, kill the child process.

The problem is that JBoss continues to run in the background after sending the kill signal, as it seems that the signal does not extend to the Java process started standalone.sh.

I like the idea of ​​using Python to write system management scripts, but there are a lot of weird edge cases like this, if I wrote it in Bash, it would all just work ™.

, KeyboardInterrupt?

+4
1

, psutil:

import psutil

#..

proc = psutil.Process(process.pid)
for child in proc.children(recursive=True):
    child.kill()

proc.kill()

, subprocess - API , , os.


, , :

proc = psutil.Process(process.pid)
procs = proc.children(recursive=True)
procs.append(proc)

for proc in procs:
    proc.terminate()

gone, alive = psutil.wait_procs(procs, timeout=1)
for p in alive:
    p.kill()

, - , .


, psutil Popen, subprocess.Popen psutil.Process. subprocess.Popen. , psutil , PID , , subprocess - .

+3

All Articles