Programmatically get parent pid of another process?

后端 未结 6 1003
北恋
北恋 2020-12-02 23:12

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

I need something like getppid(some_other_pid)

相关标签:
6条回答
  • 2020-12-02 23:37

    one more way to get it from proc entry:

    cat /proc/<pid>/status | grep PPid:
    
    0 讨论(0)
  • 2020-12-02 23:42

    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

    0 讨论(0)
  • 2020-12-02 23:42

    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.

    0 讨论(0)
  • 2020-12-02 23:42

    We can use pstree command also.

    pstree -p -s <pid of the process>
    

    pstree -s gives tree of all the ancestors. Adding -p will give you the pid as well.

    Example :Assume there is a process with pid=6206. Using the pstree command

    pstree -p -s 6206
    

    You will get the process tree.

    systemd(1)───lightdm(1066)───lightdm(1191)───upstart(1360)───gnome-terminal-(5222)───bash(5229)───cpu-print(6206)
    

    Here the parent PID is 5229

    0 讨论(0)
  • 2020-12-02 23:48

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

    0 讨论(0)
  • 2020-12-02 23:56

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

    0 讨论(0)
提交回复
热议问题