[ACCEPTED]-How to get process's grandparent id-subprocess

Accepted answer
Score: 24

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

0

Score: 7

linux specific:

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

0

Score: 5

I don't think you can do this in a portable 4 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 3 example the following script will get you 2 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 1 have to open those files with Python.

Score: 3
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

0

Score: 0

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

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

Score: 0

I looked this up for an assignment and didn't 5 find what I was looking for, so I will post 4 here. I know this is very obvious, but it 3 stumped me for a moment. If you are the 2 one writing the grandparent's code, you 1 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());
  }
}

More Related questions