父进程如何找到导致其子进程死亡的进程的pid?

时间:2017-09-14 17:05:37

标签: c linux unix signals freebsd

当父进程由于其子进程死亡而收到SIGCHLD时,父进程如何获得导致其各自子进程死亡的进程的pid?

1 个答案:

答案 0 :(得分:0)

不幸的是,父母没有收到这些信息。来自sigaction(2)

   * SIGCHLD  fills  in si_pid, si_uid, si_status, si_utime, and si_stime,
     providing information about the  child.   The  si_pid  field  is  the
     process  ID  of  the  child; si_uid is the child's real user ID.  The
     si_status field contains the exit status of the child (if si_code  is
     CLD_EXITED),  or  the signal number that caused the process to change
     state.  The si_utime and si_stime contain the  user  and  system  CPU
     time used by the child process; these fields do not include the times
     used by waited-for children (unlike getrusage(2) and  times(2)).   In
     kernels  up to 2.6, and since 2.6.27, these fields report CPU time in
     units of sysconf(_SC_CLK_TCK).  In 2.6 kernels before 2.6.27,  a  bug
     meant  that these fields reported time in units of the (configurable)
     system jiffy (see time(7)).

因此,获取信息的唯一方法(除合作之外,不会为SIGKILL分叉)是ptrace(2)孩子并等待它接收信号。< / p>

使用ptrace对于这个答案来说太复杂了。可能你可以将你的代码基于strace(1),它以非侵入方式使用ptrace,并且已经允许事件过滤。