简体   繁体   中英

Multiple Fork example in C

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM