如何获取进程的祖父母ID

发布于 2024-08-11 05:42:08 字数 162 浏览 4 评论 0原文

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

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

How can i get process id of the current process's parent?
In general given a process id how can I get its parent process id?
e.g. os.getpid() can be used to get the proccess id, and os.getppid() for the parent, how do I get grandparent,

My target is linux(ubuntu) so platform specific answers are ok.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

无戏配角 2024-08-18 05:42:08

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

By using 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>
>>> 
败给现实 2024-08-18 05:42:08

Linux特定:

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

linux specific:

os.popen("ps -p %d -oppid=" % os.getppid()).read().strip()
っ左 2024-08-18 05:42:08

我认为你不能以可移植的 Python 方式做到这一点。但有两种可能性。

  1. 该信息可通过 ps 命令获取,以便您可以对其进行分析。
  2. 如果您的系统具有 proc 文件系统,则可以打开文件 /proc//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 打开这些文件。

I don't think you can do this in a portable Python fashion. But there are two possibilities.

  1. The information is available from the ps command so you could analyze that.
  2. If you have a system with the proc file systems, you can open the file /proc/<pid>/status and search for the line containing PPid:, then do the same for that PID.

For example the following script will get you your PID, PPID and PPPID, permissions willing:

#!/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}"

produces:

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

Obviously, you'd have to open those files with Python.

痴梦一场 2024-08-18 05:42:08
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
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
橙味迷妹 2024-08-18 05:42:08

我认为在一般情况下你不能便携地做到这一点。

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

I do not think you can do this portably in the general case.

You need to get this information from the process list (e.g. through the ps command), which is obtained in a system-specific way.

够钟 2024-08-18 05:42:08

我查了一下这个作业,但没有找到我想要的东西,所以我会在这里发布。我知道这是很明显的,但它让我困惑了一会儿。如果您是祖父母代码的编写者,您可以:

#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());
  }
}

I looked this up for an assignment and didn't find what I was looking for, so I will post here. I know this is very obvious, but it stumped me for a moment. If you are the one writing the grandparent's code, you can just:

#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());
  }
}
无人问我粥可暖 2024-08-18 05:42:08

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

If you have a POSIX-compliant 'ps' command, which allows you to specify the columns you want, like this:
ps -o pid,ppid

You could then try:

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])

Now you can do:

parent[ parent[pid] ]

You could even write a function to list a process' ancestors:

def listp(pid):
    print(pid)
    if parent.has_key(pid):
        listp( parent[pid] )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文