Parent 进程有多个 child 和 2 child 进程有一个 child 进程

Parent process has multiple child and 2 child process has a child process

我有一个 parent 进程,我想从中创建 4 个 child 进程,其中 2 个 child 进程各有一个 child 进程。

我能够从 parent 创建 4 个 child 进程。但是当我尝试为 2 child 进程创建 child 进程时,我有一个无限循环。 我使用循环来创建 4 个进程并添加了一个条件,即当创建第二个 child 进程和第四个 child 进程时,为每个进程创建一个 child 进程。

来源:

#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) 在布尔上下文中被评估,这始终为真。所以每个 child 进入 if 块并分叉它自己的 child.

请改用比较运算符,如果您希望第二个和第四个 children 也为 fork:[=27=,则还要检查 i 是 1 还是 3 ]

if ((i == 1) || (i == 3))

其次,在 if(fork()==0) 块的末尾,child 过程继续进行 for 循环的下一次迭代。因此每个 child 将调用循环和分叉的 parent 行为。这导致创建的进程比预期的多。

您需要在此块的末尾添加 exit 语句。另外,一定要#include <stdlib.h>定义为exit:

if (fork()==0)
{
    ...
    exit(0);
}

另一件有用的事情:在循环结束时,让所有 children 的 parent wait 完成。否则,它可能会在其 children 之前 exit,而 children 会将进程报告为 parent

所以在这些修复之后,代码看起来像这样:

#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;
}

您正在将值 1 分配给 i 而不是比较。

if(i = 1)

应该是

if(i == 1)

如果您打算测试 i 和值 1 是否相等。当 i 始终设置为值 1 时,分配给循环控制变量会创建一个无限循环。

但是,根据您的描述,您希望为 4 个初始 child 进程中的第二个和第四个进程创建一个 child 进程,这还没有完成您想要的。

鉴于4个原children的约束,可以写

if((i & 1) != 0)

对于值 1 和 3 的计算结果为 true,其中设置了 i 的二进制表示的最低位。