How to get a grandparents/ancestors process ID?

牧云@^-^@ 提交于 2021-02-11 04:35:23

问题


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

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.


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/22159006/how-to-get-a-grandparents-ancestors-process-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!