[LCP]wait, waitpid - help

Andrew Weaver Andrew.Weaver at tecnomen.fi
Wed Feb 20 18:15:16 UTC 2002


pid=wait(&stat); - Your process will be suspended until either it receives a
signal to terminate or to be handled by a signal handler or until *a* child
has exited. 

If a child has already exited (and is now a zombie) the function will return
immediately and the child's resources freed up.

In status will be (surprise!) some info on the exit status of the child.
Various macros exist to interpret them. However, you should check the return
value (pid in the above case) for -1 indicating error otherwise it is the
pid of the exited child.

For waitpid you have similar but can specify precisely what child to wait
for based on the value of arg # 1 (pid of target child). You have used -1
which means "any child" and is equivalent to plain old wait in that respect.
WNOHANG (note spelling) means that if no child has exited when I give you
this call,  do not wait but return immediately.

You can recognise if you have returned because the child exited or not by
looking at the return value from the call. If it is zero, you returned
because the child did not exit, -1 is error. In both cases, errno probably
tells you a tad more.

Any other value should be the pid of the child that just exited.

See man wait (section 2).



> -----Original Message-----
> From:	Srinath [SMTP:redindian at nettaxi.com]
> Sent:	Monday, February 18, 2002 2:30 AM
> To:	linuxcprogramming at lists.linux.org.au
> Subject:	[LCP]wait, waitpid - help
> 
> Hello All,
>  
> the following is a handler for SIGCHLD signal in a program.
> this function was written to prevent zombies and to terminate the 
> child by catching the SIGCHLD.
>  
> void sig_chld()
> {
>   pid_t pid;
>   int stat;
>  
>  pid=wait(&stat);
>  printf("child %d terminated \n",pid);
>  return ; 
> }
>  
> now, i want to know what happens when  " pid=wait(&stat) " statement
> executes. how the child terminates (without becoming a zombie) . what is 
> the significance of "&stat ".
> also in case of waitpid(-1,&stat, WNOHNG) --what happens here
>  
>  
> Thanks 
> Srinath



More information about the linuxCprogramming mailing list