How to wait for *all* children to return ?
- From: loudking <loudking@xxxxxxxxx>
- Date: 17 May 2007 03:17:34 -0700
Question: write a program which creates 5 processes (in addition to
itself). One of these processes must display 1, another must display
2
.... the last one displays 5. The parent process waits until all other
processes are finished, then returned.
My solution is that
/* Header files omitted */
#define NUMBER_PROCESS 5
void sig_chld(int sig)
{
pid_t pid;
int stat;
while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
{
;
}
signal(SIGCHLD, sig_chld);
}
int main(int argc, char *argv[])
{
pid_t pid = getpid();
int i;
signal(SIGCHLD, sig_chld);
for (i = 0; i < NUMBER_PROCESS && pid > 0; i++)
{
pid = fork();
if (pid < 0)
{
perror("Error fork");
exit(-1);
}
else if (pid == 0)
{
printf("%d\n", i+1);
}
}/* for i */
return 0;
}
Should I add a for loop outside the while loop in sig_chld function
to
make sure that exactly 5 child termination are captured?
.
- Follow-Ups:
- Re: How to wait for *all* children to return ?
- From: Chris Dollin
- Re: How to wait for *all* children to return ?
- Prev by Date: Personal Computers (PC's) contains a lot of info
- Next by Date: Re: How to wait for *all* children to return ?
- Previous by thread: Personal Computers (PC's) contains a lot of info
- Next by thread: Re: How to wait for *all* children to return ?
- Index(es):
Relevant Pages
|