Issue
I checked the man page for waitpid, but the ERROR section indicates:
ECHILD (for waitpid() or waitid()) The process specified by pid (waitpid()) or idtype and id (waitid()) does not exist or is not a child of the calling process. (This can hap‐pen for one's own child if the action for SIGCHLD is set to SIG_IGN. See also the Linux Notes section about threads.)
Why then does calling waitpid on a non-child process after attaching to it with the ptrace system call not produce an ECHILD error?
Other answers state that ptrace and waitpid can wait for non-child processes to exit, but do not explain why.
Solution
For example, The Open Group Base Specifications Issue 6
IEEE Std 1003.1, 2004 Edition states in rationale for wait
/waitpid
:
[...] The WUNTRACED flag is used only in conjunction with job control on systems supporting job control. Its name comes from 4.3 BSD and refers to the fact that there are two types of stopped processes in that implementation: processes being traced via the ptrace() debugging facility and (untraced) processes stopped by job control signals. [...]
Alas the specification does not provide the ptrace
call:
Since ptrace() is not part of this volume of IEEE Std 1003.1-2001 [...]
What I understand from this is that wait
/waitpid
provide such possible functionality whose implementation is left to OS designers.
For example this answer may help you to understand what “trick“ is used in Linux kernel: How does ptrace work in Linux?.
Thus the wait
/waitpid
can be notified of state events from attached processes but those same processes have a preserved parenthood relation.
Linux man page for ptrace
says:
PTRACE_ATTACH
Attach to the process specified in pid, making it a tracee of the calling process. The tracee is sent a
SIGSTOP
, but will not necessarily have stopped by the completion of this call; usewaitpid(2)
to wait for the tracee to stop. See the "Attaching and detaching" subsection for additional information.
Answered By - Jean-Baptiste Yunès Answer Checked By - David Marino (WPSolving Volunteer)