Patch below corrects the long standing and well known problem with the ptrace(2) making the debuggee an orphan. Since the tracking for orphans was added to properly handle the delivery of SIGCHLD to real parent, it can also be reused for other things.
Among them are the problem with inferior(9) looping due to the process tree becoming a graph instead of tree if the parent is traced by child. Another kind of issues is due to the use of p_oppid to restore the original parent/child relationship, because real parent could already exited and its pid reused (noted by mjg).
Patch adds the function proc_realparent(9), which calculates the parent for given process. It uses the trick of finding the head element of the p_orphan list and than stepping back to its container to find the parent process. If the parent has already exited, the init(8) is returned.
I moved the P_ORPHAN and the new helper flag from the p_flag* to new p_treeflag field of struct proc, which is protected by proctree lock instead of proc lock. This makes the list traversals much simpler, because you do not need to relock proc locks for all process which are found. The orphans relationship is managed under the proctree_lock already.
The remaining uses of p_oppid in ptrace(PT_DETACH) and process reapping are replaced by proc_realparent(9).