linux:以编程方式获取另一个进程的父pid?

时间:2022-11-24 15:49:54

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

我试过谷歌,但发现getppid()获取当前进程的父pid。

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.

我需要像getppid(some_other_pid)之类的东西,有这样的东西吗?基本上取一些进程的pid并返回父进程'pid。

5 个解决方案

#1


23  

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

我认为最简单的事情是打开“/ proc”并解析内容。

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

你会发现ppid是/ proc / pid / stat的第4个参数

#2


10  

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

或者从unix shell中你可以尝试ps -p -o ppid =

#3


4  

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.

我迟到了7年,但是对于任何可能偶然发现这个问题的人来说,这是OS X上的替代解决方案。这里发布的其他答案都是正确的,sysctl()将完成这项工作,但你也可以使用proc_pidinfo获取关于流程的许多有用信息。

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

显然,需要进行额外的错误检查。

#4


2  

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

您可以查看sysctl()系统调用和此链接。

#5


0  

one more way to get it from proc entry:

从proc条目中获取它的另一种方法:

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

#1


23  

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

我认为最简单的事情是打开“/ proc”并解析内容。

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

你会发现ppid是/ proc / pid / stat的第4个参数

#2


10  

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

或者从unix shell中你可以尝试ps -p -o ppid =

#3


4  

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.

我迟到了7年,但是对于任何可能偶然发现这个问题的人来说,这是OS X上的替代解决方案。这里发布的其他答案都是正确的,sysctl()将完成这项工作,但你也可以使用proc_pidinfo获取关于流程的许多有用信息。

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

显然,需要进行额外的错误检查。

#4


2  

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

您可以查看sysctl()系统调用和此链接。

#5


0  

one more way to get it from proc entry:

从proc条目中获取它的另一种方法:

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