代码之家  ›  专栏  ›  技术社区  ›  Anurag Uniyal

如何获取进程的祖父母ID

  •  6
  • Anurag Uniyal  · 技术社区  · 15 年前

    如何获取当前进程父进程的进程ID?
    通常,如果给定了进程ID,如何获取其父进程ID?
    例如,os.getpid()可用于获取进程ID,而os.getppid()可用于获取父进程ID,如何获取祖父母,

    我的目标是Linux(Ubuntu),所以平台特定的答案是可以的。

    6 回复  |  直到 8 年前
        1
  •  7
  •   pixelbeat    15 年前

    Linux专用性:

    os.popen("ps -p %d -oppid=" % os.getppid()).read().strip()
    
        2
  •  21
  •   Giampaolo Rodolà    8 年前

    通过使用psutil( https://github.com/giampaolo/psutil ):

    >>> import psutil
    >>> psutil.Process().ppid()
    2335
    >>> psutil.Process().parent()
    <psutil.Process (pid=2335, name='bash', cmdline='bash') at 140052120886608>
    >>> 
    
        3
  •  4
  •   tzot    15 年前

    我认为你不能用一种可移植的python方式来做这个。但有两种可能性。

    1. 信息可从 ps 命令,以便您可以分析它。
    2. 如果你有一个系统 proc 文件系统,您可以打开文件 /proc/<pid>/status 搜索包含 PPid: ,然后对该PID执行相同的操作。

    例如,下面的脚本将为您提供PID、PPID和PPPID,以及所需的权限:

    #!/bin/bash
    pid=$$
    ppid=$(grep PPid: /proc/${pid}/status | awk '{print $2'})
    pppid=$(grep PPid: /proc/${ppid}/status | awk '{print $2'})
    echo ${pid} ${ppid} ${pppid}
    ps -f -p "${pid},${ppid},${pppid}"
    

    生产:

    3269 3160 3142
    UID        PID  PPID  C STIME TTY          TIME CMD
    pax       3142  2786  0 18:24 pts/1    00:00:00 bash
    root      3160  3142  0 18:24 pts/1    00:00:00 bash
    root      3269  3160  0 18:34 pts/1    00:00:00 /bin/bash ./getem.sh
    

    显然,您必须使用python打开这些文件。

        4
  •  2
  •   tzot    15 年前
    from __future__ import with_statement
    
    def pnid(pid=None, N=1):
        "Get parent (if N==1), grandparent (if N==2), ... of pid (or self if not given)"
        if pid is None:
            pid= "self"
    
        while N > 0:
            filename= "/proc/%s/status" % pid
            with open(filename, "r") as fp:
                for line in fp:
                    if line.startswith("PPid:"):
                        _, _, pid= line.rpartition("\t")
                        pid= pid.rstrip() # drop the '\n' at end
                        break
                else:
                    raise RuntimeError, "can't locate PPid line in %r" % filename
            N-= 1
    
        return int(pid) # let it fail through
    
    
    >>> pnid()
    26558
    >>> import os
    >>> os.getppid()
    26558
    >>> pnid(26558)
    26556
    >>> pnid(N=2)
    26556
    >>> pnid(N=3)
    1
    
        5
  •  0
  •   ddaa    15 年前

    在一般情况下,我认为你做不到这一点。

    您需要从流程列表(例如,通过 ps 命令),以系统特定的方式获取。

        6
  •  0
  •   Nick Dixon    15 年前

    如果您有一个符合POSIX的“ps”命令,它允许您指定所需的列,如下所示: ps -o pid,ppid

    然后您可以尝试:

    import os
    import re
    
    ps = os.popen("ps -o pid,ppid")
    ps.readline()    # discard header
    lines = ps.readlines()
    ps.close
    
    procs = [ re.split("\s+", line.strip()) for line in lines ]
    
    parent = {}
    for proc in procs:
        parent[ int(proc[0]) ] = int(proc[1])
    

    现在你可以做到:

    parent[ parent[pid] ]
    

    甚至可以编写一个函数来列出进程的祖先:

    def listp(pid):
        print(pid)
        if parent.has_key(pid):
            listp( parent[pid] )