I have executed your code, by printing at first the pid of the root process, to obtain this output:
$ pru
start: pid == 6024
I am the process 6025 and my father is 6024
I am the process 6024 and my father is 5524
I am the process 6027 and my father is 6025
I am the process 6028 and my father is 6024
I am the process 6026 and my father is 6024
I am the process 6029 and my father is 6026
I can reorder the data to build the tree, starting by process 6024
:
I am the process 6024 and my father is 5524
I am the process 6026 and my father is 6024
I am the process 6029 and my father is 6026
I am the process 6025 and my father is 6024
I am the process 6027 and my father is 6025
I am the process 6028 and my father is 6024
you could have done the same, by looking that process 6024 shows a completely different parent (in this case 5524) that is not in the list of processes.
In your case, the output is bad (or you have retouched it or the posted code is not the same that produced that output) as the process tree is not the one shown here.
- process
6024
executes the full loop, and so, executes three fork()
s, creating tree more processes (two in the loop and one after it).
- two of these processes (the ones created in the loop:
6025
and 6026
) break
the loop, and execute the fork()
outside the loop, creating one process each, by calling the fork()
that is outside the loop. giving you processes 6027
and 6029
, resp.
The output you show, cannot be arranged in this tree structure, if we sort the lines:
I am the process 2133 and my father is 2127
I am the process 2134 and my father is 2133
I am the process 2137 and my father is 778
I am the process 2135 and my father is 778
I am the process 2138 and my father is 778
I am the process 2136 and my father is 778
as only process 2134
is a child of other process... and that is not a tree.
Note
I have read in the comments to your question that for some reason the children have been reparented to the shell. In UNIX no process is reparented to another parent, except when it's parent exit()
s *by any means), in which case, they are reparented to process with PID=1 (the init
or systemd
process, and this is what makes pid 1 special) So your process can be reparented, but never to a different process than the one with PID=1. Indeed, you can check if your parent has died, by testing the result of getppid()
as, if it returns 1
, then your parent is not alive anymore.
Finally, there's plenty of documentation about this schema and the unix process structure, but if I had to recommend you to read about it, I should refer you to the POSIX specifications, available from The Open Group