简体   繁体   English

Python杀死一个子进程

[英]Python Killing a Subprocess

Python 2.7, Ubuntu 16.04 Python 2.7,Ubuntu 16.04

We have a proprietary mathematical package we purchased that we use for calculations. 我们有一个购买的专有数学包,用于计算。 We are trying to build a process that kills the subprocess of that package after running for 10 seconds. 我们正在尝试构建一个进程,该进程在运行10秒后会杀死该程序包的子进程。

The solution below kills the do_math() function after 10 seconds as expected. 下面的解决方案按预期在10秒钟后杀死了do_math()函数。 However the solve launches a sub process with it's own pid. 但是, solve使用自己的pid启动子流程。 So, doing a ps aux shows that it runs under its own name, and not under the python name. 因此,执行ps aux显示它以自己的名称运行,而不是以python名称运行。

Is there any way to track and kill a pid that has been launched this way in python? 有什么方法可以跟踪和杀死已在python中以这种方式启动的pid?

def do_math():
    status = solve() #launches the package

#Start function as a process
k = multiprocessing.Process(target=do_math)
k.start()

# Wait for 10 seconds or until process finishes
k.join(10)

# If thread is still active
if k.is_alive():
    print k.pid
    os.kill(k.pid, signal.SIGINT)

Assuming that the solve function is doing something nasty that you can't change, there is no easy or clean way to do this. 假设solve函数正在做一些您无法更改的令人讨厌的事情,那么没有简单或干净的方法可以做到这一点。

One possibility is to spawn the child in its own group and then nuke the group… but that's not trivial to manage with multiprocessing , and it may not even work depending on how solve launches the grandchildren. 一种可能是将孩子放在自己的小组中,然后对小组进行核对……但是通过multiprocessing进行管理并multiprocessing ,而且甚至可能solve取决于solve如何释放孙子孙辈。

An even hackier way, but probably both easier and more likely to work, is to manually walk the child's process tree to find and kill any grandchildren either before or after killing the child. 更加骇人听闻的方法(但可能更容易且更可能起作用)是手动杀死孩子的进程树,以在杀死孩子之前或之后找到并杀死所有孙子。 The simplest way to do that is probably a third-party library like psutil . 最简单的方法可能是像psutil这样的第三方库。 It would look something like this: 它看起来像这样:

# Shortly after launching k
p = psutil.Process(k.pid)

# Later, right before killing k
for child in p.children():
    p.send_signal(signal.SIGINT)

If you want to kill them after the child (I assume there's a reason you're sending SIGINT instead of SIGTERM , so this might matter), you'll want to copy p.children() first before killing k . 如果您想在孩子之后杀死它们(我认为您是发送SIGINT而不是SIGTERM的原因,那么这可能很重要),您需要在杀死k之前先复制p.children()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM