Reputation: 4278
I am trying to have a program that uses multiple forks.
I used this example to get myself started
Multiple fork() Concurrency
it works perfectly as is. However, when I try to add a print statement in the child like this:
if ((p = fork()) == 0) {
// Child process: do your work here
printf("child %i\n", ii);
exit(0);
}
The process never finishes. How can I do stuff in the child and get the parent to still finish execution of the program?
Upvotes: 0
Views: 1493
Reputation: 3900
In your example code
if (waitpid(childPids[ii], NULL, WNOHANG) == 0) {
should be
if (waitpid(childPids[ii], NULL, WNOHANG) == childPids[ii]) {
because of
waitpid(): on success, returns the process ID of the child whose state has changed; on error, -1 is returned; if WNOHANG was specified and no child(ren) specified by pid has yet changed state, then 0 is returned.
Reference: http://linux.die.net/man/2/waitpid
Upvotes: 3