Reputation: 3
i want one parent process to create 10 child processes, but how can i make the parent process to wait for all child processes?
i have this given code in C
for(int cnt = 1; cnt<=10; cnt++) {
switch ( pid = fork() ) {
case -1:
perror("error");
break;
case 0:
printf("%d: child process, my PID=%d and PPID=%d\n", cnt, getpid(), getppid() );
sleep(10);
exit(0);
break;
default:
printf("%d: parent process, my PID=%d and PPID=%d\n", cnt, getpid(), getppid() );
sleep(10);
}
}
}
i tried with wait and waitpid in the default part, but it seems that the parent process only waits for the next child process to exit. how can i make it wait for all 10 child processes to exit?
Upvotes: 0
Views: 190
Reputation: 2659
You have to loop over the child processes and, if you want, get your status.
Like this:
int i, pid, status;
for (i=0; i<10N; i++) {
pid=wait(&status);
printf("Arrived child with pid %d - status %d\n", pid, status);
}
Upvotes: 0