简体   繁体   中英

fork and waitpid in C

I have this piece of code, maybe I'm missing something:

const int NPROCESSES = 32;   
pid_t pids[128];

for (int i = 0; i < NPROCESSES;i ++) {
   pids[i] = fork();
   if (!pids[i]) {  
       /*... other code ...*/
       exit(0);
   }
}

for (int i = 0; i < NPROCESSES; i++)
    waitpid(pids[i], 0, 0);

The program should launch 32 processes and wait until all processes are terminated. But sometimes the program get blocked with child zombie processes. Where am I wrong?

Using:

waitpid(pids[i], 0, 0);

you specify an exact order in which the parent will reap its children: it will be the same order as they were created.

As a result, if one of the children blocks or delays for any reason, and some other child which was created later has already finished (and called exit() ), the latter will remain in a zombie state, until the parent reaps the former child first.

So if, for example, the process created in the first iteration of the loop needs 1min to complete and the rest 31 processes are completed in 1sec, you're be able to observe 31 zombie processes waiting to be reaped by their parent, who (the parent) will wait to reap that one delayed process first.

To change this behavior, the parent can use:

waitpid(-1, NULL, 0);

instead. A value equal to -1 in the first argument of waitpid() means it will reap any of the child processes, quoting from man 2 waitpid :

The value of pid can be:

< -1

meaning wait for any child process whose process group ID is equal to the absolute value of pid.

-1

meaning wait for any child process.

0

meaning wait for any child process whose process group ID is equal to that of the calling process.

> 0

meaning wait for the child whose process ID is equal to the value of pid.

Alternatively, you can just use:

wait(NULL);

which is the same as waitpid(-1, NULL, 0) .

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