问题
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