如何获得祖父母/祖先进程ID? [英] How to get a grandparents/ancestors process ID?

查看:63
本文介绍了如何获得祖父母/祖先进程ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 - 如果可能的话 - 如何获取进程的祖父母(或更多)的 pid.

I would like to know - if possible - how to get the pid of a process' grandparent (or further).

更具体地说,我希望一个进程在进程树中打印其深度.例如,当从以下开始时:

To be more specific, I want for a process to print its depth in a process tree. For example, when starting with the following:

int main() {
    int creator_id = (int) getpid();
    pid_t pid1 = fork();
    pid_t pid2 = fork();
    pid_t pid3 = fork();        

    //print depth in process tree of each process

    return 0;
}

根据我的理论,这棵树看起来像这样:

According to my theory, the tree will look like this:

               0
              /|\ 
             / | \
            /  |  \
           0   0   0
          / \  |            
         0   0 0  
        /            
       0

所以我的第一个想法是以某种方式查看在找到创建者的 pid 之前我必须上升的频率.

So my first idea was to somehow see how often I have to go up until I find the creator's pid.

作为一个小旁注:我也想知道是否可以从下往上进行打印,意味着最深层次的所有过程都会先打印.

As a little sidenote: I also wondered if it was possible to make the printing from bottom up, meaning that all processes in the deepest level would print first.

推荐答案

如何获取进程的祖父(或进一步)的 pid.

how to get the pid of a process' grandparent (or further).

这取决于您使用的操作系统,因为您在示例中使用 fork() 创建新进程,我想您使用的是一些类 Unix 系统.

This depends on which operating system you are using, since you use fork() to create new process in your example, I suppose you are using some Unix-like system.

如果您使用 Linux 并且知道进程的 pid,则可以从 /proc/[pid]/stat,该文件中的第四个字段.通过这个父子链,你可以找到一个进程的所有祖先.

If you are using Linux and know the pid of a process, you could get its parent process' pid from /proc/[pid]/stat, the fourth field in that file. Through this parent-child chain, you could find a process' all ancestors.

这篇关于如何获得祖父母/祖先进程ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆