Home > Archive > Unix Programming > July 2006 > waitpid with WNOHANG multiple times?
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
waitpid with WNOHANG multiple times?
|
|
| skillzero@gmail.com 2006-07-19, 8:02 am |
| If you fork/exec a child process and call waitpid with WNOHANG with
that child's pid before that child has finished, will that child
process be reaped when it does exit or does waitpid with WNOHANG only
reap the process if it has already exited by the time waitpid is
called?
I want to start a process then poll it with waitpid( pid, WNOHANG ) and
sleep( 1 ) to see if it finishes in 10 seconds. This is only for
debugging code to see if a process takes too long to run (without
needing a bunch of SIG_CHLD stuff).
I haven't been able to find a definitive answer as to whether it should
be safe to call waitpid with WNOHANG multiple times for a process
before it exits (and once after it exits). I'm worried that if the
first waitpid sets some "has been waited on" flag that causes the
process to be reaped automatically when it exits then a future call to
waitpid for that pid may end up waiting on a completely different
process if the pid has been reused.
| |
| Rainer Temme 2006-07-19, 8:02 am |
| skillzero@gmail.com wrote:
> If you fork/exec a child process and call waitpid with WNOHANG with
> that child's pid before that child has finished, will that child
> process be reaped when it does exit or does waitpid with WNOHANG only
> reap the process if it has already exited by the time waitpid is
> called?
if it would be reaped under these circumstances you wouldn't have a
chance to see the exit-code of the child.
Therefore the childprocess can only be reaped if waitpid is called
after the child exited.
see this sniplet of code ...
$ cat x.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int child(coid)
{
int pid;
pid=fork();
if (pid==0)
{
sleep(5);
_exit(77);
}
return(pid);
}
int main(int c,char **v)
{
int pid;
int rc,state;
pid=child();
for(;;)
{
state=0;
rc=waitpid(pid,&state,WNOHANG);
printf("waitpid(%d)=%d [%d/%x]\n",pid,rc,state,state);
sleep(1);
}
}
$ x
waitpid(25516)=0 [0/0]
waitpid(25516)=0 [0/0]
waitpid(25516)=0 [0/0]
waitpid(25516)=0 [0/0]
waitpid(25516)=0 [0/0]
waitpid(25516)=25516 [19712/4d00]
waitpid(25516)=-1 [0/0]
waitpid(25516)=-1 [0/0]
waitpid(25516)=-1 [0/0]
waitpid(25516)=-1 [0/0]
.... Rainer
|
|
|
|
|