简体   繁体   English

C中的fork和waitpid

[英]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. 该程序应启动32个进程,并等待所有进程终止。 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. 结果,如果一个子级由于某种原因阻塞或延迟,并且稍后创建的另一个子级已经完成(并称为exit() ),则后者将保持僵尸状态,直到父级获得前者孩子第一。

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. 因此,例如,如果在循环的第一次迭代中创建的进程需要1分钟才能完成,而其余31个进程在1秒内完成,则您可以观察到31个僵尸进程正在等待其父(他们(家长)将首先等待获得该延迟的过程。

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 : waitpid()的第一个参数中,等于-1的值意味着它将引用man 2 waitpid引用任何子进程:

The value of pid can be: pid的值可以是:

< -1

meaning wait for any child process whose process group ID is equal to the absolute value of pid. 意思是等待任何进程组ID等于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. 意思是等待任何进程组ID与调用进程的ID相等的子进程。

> 0

meaning wait for the child whose process ID is equal to the value of pid. 意思是等待进程ID等于pid值的子进程。

Alternatively, you can just use: 或者,您可以只使用:

wait(NULL);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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