如何获得进程的祖父母id

时间:2009-11-13 10:13:58

标签: python linux process subprocess

如何获取当前进程父进程的进程ID?
一般来说,给定一个进程ID如何获取其父进程ID?
例如os.getpid()可用于获取proccess id,而os.getppid()用于父级,如何获得祖父母,

我的目标是linux(ubuntu),所以平台特定的答案都可以。

7 个答案:

答案 0 :(得分:22)

使用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>
>>> 

答案 1 :(得分:7)

linux specific:

os.popen("ps -p %d -oppid=" % os.getppid()).read().strip()

答案 2 :(得分:4)

我认为你不能用便携式Python方式做到这一点。但有两种可能性。

  1. 可以从ps命令获取该信息,以便分析该信息。
  2. 如果您的系统具有proc文件系统,则可以打开文件/proc/<pid>/status并搜索包含PPid:的行,然后对该PID执行相同操作。
  3. 例如,以下脚本将为您提供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打开这些文件。

答案 3 :(得分:2)

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

答案 4 :(得分:0)

在一般情况下,我认为你不能这样做。

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

答案 5 :(得分:0)

如果你有一个符合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] )

答案 6 :(得分:0)

我查找了一份作业,但没有找到我要找的内容,所以我会在这里发布。我知道这很明显,但它难倒了我片刻。如果您是编写祖父母代码的人,您可以:

#include <stdio.h>
#include <sys/types.h>
#include<sys/wait.h>
#include <unistd.h>

int main(void) {
  int grandpa = getpid();
  int id = fork();
  if (id == 0) {
    int id2 = fork();
    if (id2 == 0) {
      printf("I am the child process C and my pid is %d. My parent P has pid %d. My grandparent G has pid %d.\n", getpid(), getppid(), grandpa);
    } else {
      wait(NULL);
      printf("I am the parent process P and my pid is %d. My parent G has pid %d.\n", getpid(), getppid());
    }
  } else {
    wait(NULL);
    printf("I am the grandparent process G and my pid is %d.\n", getpid());
  }
}