How to wait for *all* children to stop?

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?

Thanks!
 
W

William Ahern

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.
while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
{
pid_t pid = getpid();
int i;

pid = fork();
if (pid < 0)
{
<snip>

Repost on comp.unix.programmer, since these Unix interfaces are off-topic on
comp.lang.c, and your question involves the behavior of these interfaces,
not of the C language.

I'm inclined to comment further, but many folks here might not know the
semantics of fork() and waitpid()--e.g. many Windows programmers--and so I
might be able to get away w/ completely misleading you (accidentally, of
course).

- Bill
 
I

Ian Collins

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

Try comp.unix.programmer.
 
K

Kenny McCormack

Try comp.unix.programmer.

IOW, nobody here gives a sh*t. They are, by their own admission,
dumbasses who've never heard of any of the things that you mention.
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top