How to wait for *all* children to return ?

L

loudking

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?
 
C

Chris Dollin

loudking said:
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.

Answer: fork etc are not part of Standard C. Your likely best bet
is comp.unix.programmer for questions about child support.

PS
while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
{
;
}

That's a lot of room for a no-op. What's wrong with `{}` either
after the `)` or underneath the loop test?

PPS

You never use `pid`. So there's no point in assigning to it.
The you can dispose of the redundant brackets round the
condition.

PPS

You never use the value of `stat`. I wonder if there's a way
in which you can avoid having a `stat` variable at all?

PPPS

You're clearly using some extensions to C, but is it really necessary
to use `exit(-1)` rather than `exit(EXIT_FAILURE)` or even -- since
we're conveniently inside `main` -- `return EXIT_FAILURE`?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top