Why doesn't waitid block until child terminates?

那年仲夏 提交于 2019-12-11 19:55:21

问题


void *stack;
stack = malloc(STACK_SIZE);
if (-1 == clone(child_thread, stack + STACK_SIZE, 0, NULL)) {                                                                                                                                                                           
    perror("clone failed:");
}   
while(waitid(P_ALL, 0, NULL, WEXITED) != 0){ 
    perror("waitid failed:");
    sleep(1);
}   

The manual says:

If a child has already changed state, then these calls return immediately. Otherwise they block until either a child changes state

But in fact it returns immediately :

waitid failed:: No child processes
waitid failed:: No child processes
...

Any advice?


回答1:


You are using PID options. Look further in the man page:

The following Linux-specific options are for use with children created using clone(2); they cannot be used with waitid():

   __WCLONE
          Wait  for "clone" children only.  If omitted then wait for "non-
          clone" children only.  (A "clone" child is one which delivers no
          signal, or a signal other than SIGCHLD to its parent upon termi-
          nation.)  This option is ignored if __WALL is also specified.

   __WALL (Since Linux 2.4) Wait for  all  children,  regardless  of  type
          ("clone" or "non-clone").

   __WNOTHREAD
          (Since  Linux  2.4) Do not wait for children of other threads in
          the same thread group. This was the default before Linux 2.4.



回答2:


I do not know the specifics of what you are trying to get done here, but by using waitid in the following way might help:

#include <sys/types.h>
#include <sys/wait.h>

...

siginfo_t signalInfo;
waitid(P_ALL, 0, &signalInfo, WEXITED | WSTOPPED | WNOWAIT | WNOHANG);

Then check for the following in signalInfo to know what happened whenever child exits:

signalInfo.si_signo : For Signal Number
signalInfo.si_code : Usually SIGCHLD
signalInfo.si_errno) : Any error code set
signalInfo.si_status : For exit code of the child code

Note: Using WNOWAIT makes the OS preserve the child process resource usage even after it is killed. You may/may not use this option. If you do, you will have to explicitly call waitid on the child again without the WNOWAIT option.

Reference: See man pages for waitid for more information on this.



来源:https://stackoverflow.com/questions/13853524/why-doesnt-waitid-block-until-child-terminates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!