开发者

Multiple Fork example in C

开发者 https://www.devze.com 2023-04-10 15:22 出处:网络
I am trying to have a program that uses multiple forks. I used this example to get myself started Multiple fork() Concurrency

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 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

0

精彩评论

暂无评论...
验证码 换一张
取 消