当父进程死亡时,如何杀死用subprocess.check_output()创建的python子进程?

时间:2013-10-18 10:39:27

标签: python linux subprocess

我在linux机器上运行python脚本,使用subprocess.check_output()创建子进程,如下所示:

subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)

问题在于,即使父进程终止,子进程仍在运行。 当父母去世时,我有什么办法可以杀死孩子的过程吗?

5 个答案:

答案 0 :(得分:24)

是的,您可以通过两种方法实现这一目标。它们都要求您使用Popen而不是check_output。第一个是更简单的方法,使用try..finally,如下所示:

from contextlib import contextmanager

@contextmanager
def run_and_terminate_process(*args, **kwargs):
try:
    p = subprocess.Popen(*args, **kwargs)
    yield p        
finally:
    p.terminate() # send sigterm, or ...
    p.kill()      # send sigkill

def main():
    with run_and_terminate_process(args) as running_proc:
        # Your code here, such as running_proc.stdout.readline()

这将捕获sigint(键盘中断)和sigterm,但不是sigkill(如果你用-9杀死你的脚本)。

另一种方法有点复杂,并使用ctypes的prctl PR_SET_PDEATHSIG。一旦父母出于任何原因退出(即使是sigkill),系统将向孩子发送信号。

import signal
import ctypes
libc = ctypes.CDLL("libc.so.6")
def set_pdeathsig(sig = signal.SIGTERM):
    def callable():
        return libc.prctl(1, sig)
    return callable
p = subprocess.Popen(args, preexec_fn = set_pdeathsig(signal.SIGTERM))

答案 1 :(得分:21)

问题在于使用subprocess.check_output - 你是对的,你不能使用该接口获得子PID。请改用Popen:

proc = subprocess.Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE)

# Here you can get the PID
global child_pid
child_pid = proc.pid

# Now we can wait for the child to complete
(output, error) = proc.communicate()

if error:
    print "error:", error

print "output:", output

确保在退出时杀死孩子:

import os
import signal
def kill_child():
    if child_pid is None:
        pass
    else:
        os.kill(child_pid, signal.SIGTERM)

import atexit
atexit.register(kill_child)

答案 2 :(得分:1)

不知道具体细节,但最好的方法仍然是用信号捕捉错误(甚至可能是所有错误)并终止那里的任何剩余进程。

import signal
import sys
import subprocess
import os

def signal_handler(signal, frame):
    sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

a = subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)

while 1:
    pass # Press Ctrl-C (breaks the application and is catched by signal_handler()

这只是一个模型,你需要捕获的不仅仅是SIGINT,但这个想法可能会让你开始,你需要以某种方式检查衍生过程。

http://docs.python.org/2/library/os.html#os.kill http://docs.python.org/2/library/subprocess.html#subprocess.Popen.pid http://docs.python.org/2/library/subprocess.html#subprocess.Popen.kill

我建议重写check_output的个性化版本因为我刚刚意识到check_output真的只是为了简单的调试等,因为在执行期间你无法与它进行如此多的交互..

重写check_output:

from subprocess import Popen, PIPE, STDOUT
from time import sleep, time

def checkOutput(cmd):
    a = Popen('ls -l', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    print(a.pid)
    start = time()
    while a.poll() == None or time()-start <= 30: #30 sec grace period
        sleep(0.25)
    if a.poll() == None:
        print('Still running, killing')
        a.kill()
    else:
        print('exit code:',a.poll())
    output = a.stdout.read()
    a.stdout.close()
    a.stdin.close()
    return output

用它做任何你喜欢的事情,或许将活动执行存储在一个临时变量中,并在退出时用信号或其他方法拦截主循环的错误/关闭来终止它们。

最后,您仍然需要在主应用程序中捕获终止以安全地杀死所有孩子,最好的方法是使用try & exceptsignal

答案 3 :(得分:0)

从Python 3.2开始,有一种非常简单的方法可以做到这一点:

from subprocess import Popen

with Popen(["sleep", "60"]) as process:
    print(f"Just launched server with PID {process.pid}")

我认为这对于大多数用例来说是最好的,因为它既简单又可移植,并且避免了对全局状态的任何依赖。

如果此解决方案不够强大,那么我建议您查看有关此问题或Node.js File system capture的其他答案和讨论,因为有很多巧妙的方法可以解决提供不同交易的问题围绕可移植性,弹性和简单性的问题。 ?

答案 4 :(得分:-2)

手动你可以这样做:

ps aux | grep <process name>

获取PID(第二列)和

kill -9 <PID> -9是强行杀死它