我有一个父进程,我想从中创建 4 个子进程,其中 2 个子进程各有一个子进程。
我能够从父进程创建 4 个子进程。但是当我尝试为 2 个子进程创建子进程时,我遇到了无限循环。 我使用for循环创建了4个进程,并添加了一个条件,即当创建第二个子进程和第四个子进程时,为每个子进程创建一个子进程。
- 父项有 (child1 chil2 child3 child 4)
- child 2 有( child 5 child 6)
来源:
#include <stdio.h>
#include <unistd.h>
#include <sched.h>
#include <sys/time.h>
#include <sys/resource.h>
int main(int argc, char **argv)
{
int i;
for(i = 0; i <= 3; i++)
{
if(fork() == 0)
{
printf("process %d and his parent is %d \n",
getpid(), getppid());
if(i = 1)
{
if(fork() == 0)
{
printf("process %d and his parent is %d \n",
getpid(), getppid());
break;
}
}
}
}
return 0;
}
最佳答案
两个问题。第一:
if(i = 1)
您正在使用=
这是一个赋值而不是 ==
比较是否相等。这里实际发生的是i
被赋予值 1,并且该值 (1) 正在 bool 上下文中求值,该上下文始终为 true。所以每个 child 都输入if
阻止并 fork 自己的 child 。
改用比较运算符,并检查是否 i
如果您希望第二个和第四个 child 也这样做,则为 1 或 3 fork
:
if ((i == 1) || (i == 3))
第二,在 if(fork()==0)
的末尾 block 中,子进程继续进行 for
的下一次迭代环形。因此每个子进程都会调用父进程的循环和 fork 行为。这会导致创建的进程比预期多得多。
您需要添加 exit
语句在此 block 的末尾。另外,请务必#include <stdlib.h>
对于 exit
的定义:
if (fork()==0)
{
...
exit(0);
}
另一件事很有用:在循环结束时,有父项 wait
让所有 child 都能完成。否则,可能exit
在其子级和子级将报告进程`作为父级之前
因此,在这些修复之后,代码如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
int main(int argc, char **argv)
{
int i;
for(i = 0; i <= 3; i++)
{
if(fork() == 0)
{
printf("process %d and his parent is %d \n",
getpid(), getppid());
if ((i == 1) || (i == 3))
{
if(fork() == 0)
{
printf("process %d and his parent is %d \n",
getpid(), getppid());
exit(0);
}
while (wait(NULL) != -1);
}
exit(0);
}
}
while (wait(NULL) != -1);
return 0;
}
关于c - 父进程有多个子进程,2个子进程有一个子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33545893/