【问题标题】:Get pid of recursive subprocesses获取递归子进程的pid
【发布时间】:2017-03-23 10:20:54
【问题描述】:

场景:子进程创建了子进程等等,如何获取它的pid?

我使用 subprocess.popen 启动了第一个子进程,例如 word 文件,这个 word 文件生成了一个新的子进程,我怎样才能得到它的 pid?

【问题讨论】:

  • 你读过这个问题吗?我问了内部 pid
  • 是的,如果你有根进程的 pid,你可以通过从你的模块调用 pstree 来请求嵌套的 pid, pstree -p $pid(root_process_pid) | grep -o '([0-9]\+)' | grep -o '[0-9]\+' unix.stackexchange.com/questions/67668/…
  • 一旦你得到主进程的pid,使用psutil可能是在python中遍历进程树最简单的方法:stackoverflow.com/questions/3332043/…
  • 感谢您的解释,但它并没有帮助我尝试 parent = psutil.Process(proc.pid).parent() for child in parent.children(recursive=True): print 'parent %d child %d' % (proc.pid,child.pid) 并且没有 parent(),它没有帮助,我无法获得孩子的 pid 我得到的唯一 pid 是父亲的

标签: python python-2.7 subprocess popen pid


【解决方案1】:

使用 psutil:

parent = psutil.Process(parent_pid)
children = parent.children()
# all child pids can be accessed using the pid attribute
child_pids = [p.pid for p in children]

【讨论】:

  • 它没有帮助:( child_pids 似乎总是空的(即使确实出现了子进程)
  • 然后你的进程使用一些技术来脱离子进程。您还可以使用 psutil 查找子进程的父 pid。也许这有助于发现发生了什么。
猜你喜欢
  • 2021-08-08
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 2016-01-31
  • 2011-07-11
  • 2017-08-13
相关资源
最近更新 更多