像这样:
int childs = 5; // I want 5 childs
pid_t pid;
while (childs > 0)
{
if ((pid = fork()) == -1)
return (1); // handle this error as you want
if (pid == 0)
break;
childs--;
}
// the child go there directly
您可以使用pid_t的数组/列表来记住所有孩子,并使用waitpid检查他们的状态。
编辑:
不同方式处理孩子并通过数组记住孩子的方法:
int childs = 5; // I want 5 childs
pid_t pid[childs];
int i;
for (i=0; i < childs; ++i) {
if ((pid[i] = fork()) == -1)
return (1); // handle this error as you want
if (pid[i] == 0) {
break;
}
}
switch (i) {
case 0:
return(function0());
break;
case 1:
return(function1());
break;
case 2:
return(function2());
break;
case 3:
return(function3());
break;
case 4:
return(function4());
break;
default:
;
}
我不完全知道您要做什么,您也可以在有条件的情况下使用模(%)运算符来调用正确的函数。 我在那儿使用return,因为我们不想再停留在for循环中了,'functionx()'将完成整个新过程。 您也可以在函数中使用。
现在,您有了一个pid_t数组,因此可以循环检查孩子的状态。