【问题标题】:kill a process and its sub-processes in a python script [duplicate]在python脚本中杀死一个进程及其子进程[重复]
【发布时间】:2016-03-23 18:12:46
【问题描述】:

在我的脚本中,我得到了一个进程 ID(父/主)

对于 id 3-4 的主进程,linux 终端中正在运行几个子进程

我的要求是从那个 processid 杀死所有子进程和子进程。

我试过了

 import os
 pid = parent process id
 from  subprocess import call
 call(["pkill", "-TERM","-P", str(pid)])

但没有成功。

也试过了

 os.system('kill -9 ' + pid)  # only parent is getting killed subpid are still running.

请提出一些建议,例如按主进程 id 列出所有子进程。然后在循环中如何杀死这些子进程,然后是父进程。

kill process and its sub/co-processes by getting their parent pid by python script

遗憾的是,这对我的情况没有帮助。

【问题讨论】:

  • @JohnZwinck-也没有帮助。
  • 为什么没有帮助?您对这些解决方案有什么具体问题?
  • @Satya:我认为您需要追求的第一步是“创建一个进程组”,其中包含您以后希望杀死的所有进程。换句话说,这不仅仅是如何在 Python 中解决这个问题,而是通过使用进程组来让问题本身消失,这是在 *nix 系统上解决这个问题的常规方法。

标签: python subprocess kill-process


【解决方案1】:

使用 psutil 来做到这一点。

import signal
import psutil

def kill(ppid, signal=signal.SIGTERM):
    try:
      process = psutil.Process(ppid)
    except psutil.NoSuchProcess:
      return
    pids = process.get_children(recursive=True)
    for pid in pids:
      os.kill(pid.pid, signal)

【讨论】:

  • @Zetysz-TypeError: 不可排序的类型: str() <整数()
  • 当我打印父 ID 的类型时,它是
  • @Satya 将其设为 int
  • 可能在 pids = process.get_children(recursive=True) 中,当我打印 pids 时,有些东西需要更改 bcoz 我没有得到任何东西
  • @Satya 可能是带有ppid的进程,你给的没有子进程。
猜你喜欢
  • 1970-01-01
  • 2016-02-29
  • 2011-02-07
  • 1970-01-01
  • 2010-12-08
  • 2016-01-24
  • 1970-01-01
  • 2014-04-16
  • 2018-03-26
相关资源
最近更新 更多