I am trying to have a program that uses multiple forks.
I used this example to get myself started Multiple fork() Concurrencyit 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 s开发者_开发问答tuff in the child and get the parent to still finish execution of the program?
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
精彩评论