Programmatically get parent pid of another process?

I tried google, but found getppid() which gets the parent pid of the current process.

I need something like getppid(some_other_pid), is there such a thing? Basically takes the pid of some process and returns the parent process' pid.


Solution 1:

I think the simplest thing would be to open "/proc" and parse the contents.

You'll find the ppid as the 4th parameter of /proc/pid/stat

Solution 2:

or from a unix shell you can try ps -p <child_pid> -o ppid=

Solution 3:

I am 7 years late to the party but for anyone who may stumble upon this question, here's an alternative solution on OS X. Other answers posted here are correct and sysctl() will do the job, but you can also use proc_pidinfo to obtain a lot of useful information about a process.

#include <libproc.h>

int getppid(const pid_t pid)
{
    proc_bsdinfo info;
    proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info));
    return info.pbi_ppid;
}

Obviously, additional error checking is required.

Solution 4:

You can have a look at sysctl() system call and this link.

Solution 5:

one more way to get it from proc entry:

cat /proc/<pid>/status | grep PPid: