以编程方式获取给定 PID 的子进程列表

Cod*_*der 6 python linux ubuntu process node.js

我想获得给定 PID 的所有直接子级的列表。我可以使用/proc/proc/<PID>/task/<PID>/children不精确并且可能返回不准确的结果(请参阅此处的第 3.7 节)。我想要一种更可靠的方法来做到这一点。

我不想在 shell 命令周围使用包装器。

Ian*_*son 1

为什么不使用 psutils?

这是一个我杀死所有孩子的例子。

def infanticide(pid):
    try:
      parent = psutil.Process(pid)
    except psutil.NoSuchProcess:
      return
    children = parent.children(recursive=True)
    for p in children:
        os.kill(p.pid, signal.SIGKILL)
Run Code Online (Sandbox Code Playgroud)