当父进程死亡时,如何杀死使用 subprocess.check_output() 创建的 python 子进程? [英] How to kill a python child process created with subprocess.check_output() when the parent dies?

查看:27
本文介绍了当父进程死亡时,如何杀死使用 subprocess.check_output() 创建的 python 子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am running on a linux machine a python script which creates a child process using subprocess.check_output() as it follows:

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

问题是即使父进程死了,子进程仍在运行.当父进程死亡时,有什么方法可以杀死子进程?

The problem is that even if the parent process dies, the child is still running. Is there any way I can kill the child process as well when the parent dies?

推荐答案

您的问题在于使用 subprocess.check_output - 您是对的,您无法使用该接口获取子 PID.改用 Popen:

Your problem is with using subprocess.check_output - you are correct, you can't get the child PID using that interface. Use Popen instead:

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

为了确保您在退出时杀死孩子:

To make sure you kill the child on exit:

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)

这篇关于当父进程死亡时,如何杀死使用 subprocess.check_output() 创建的 python 子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆