在 UNIX 中创建多个 child 进程

Create multiple child processes in UNIX

我想编写一个创建 N child 个进程的 UNIX 程序,以便第一个进程创建一个 child 个进程,然后这个 child 只创建一个进程是它的 child,然后 child 的 child 创建另一个 child 等。 这是我的代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int N=3;
    int i=0;

    printf("Creating %d children\n", N);
    printf("PARENT PROCESS\nMy pid is:%d \n",getpid() );
    for(i=0;i<N;i++)
    {
        pid_t pid=fork();
        if(pid < 0)
        {
             perror("Fork error\n");
             return 1;  
        }
        else if (pid==0) /* child */
        {
            printf("CHILD My pid is:%d  my parent pid is %d\n",getpid(), getppid() );
        }
        else /* parrent */
        {
             exit(0);
        }

    }
    return 0;
}

我期望的输出格式为:

Creating 3 children
PARENT PROCESS
My pid is 1234
CHILD My pid is 4567 my parent pid is 1234
CHILD My pid is 3528 my parent pid is 4567
CHILD My pid is 5735 my parent pid is 3528

我在终端得到的输出是

Creating 3 children
PARENT PROCESS
My pid is:564
CHILD My pid is:5036  my parent pid is 564

User@User-PC ~
$ CHILD My pid is:4804  my parent pid is 1
CHILD My pid is:6412  my parent pid is 4804

问题是程序似乎没有终止。我应该使用 Ctrl+C 退出终端,这是不正常的。你能帮我解决这个问题吗?

当 parent 死亡时 children 死亡。 在您的情况下,parent 在创建所有 children 之前退出。

尝试等待 children 后再退出:

    else /* parrent */
    {
        int returnStatus;    
        waitpid(pid, &returnStatus, 0);  // Parent process waits for child to terminate.
         exit(0);
    }

尝试使用 wait(NULL) 等待进程;

pid_t child = fork();
if (child == -1)
{
  puts("error");
  exit(0);
}
else if (child == 0)
{
 // your action
}
else
{
 wait(&child);
 exit(0);
}

所以你父亲会等待子进程退出

建议的治疗方法是正确的,但陈述的原因是错误的。 Children不要与parent同归于尽。行

CHILD My pid is:4804  my parent pid is 1

清楚地表明,在 child 调用 getppid() 时,它的 parent 已经死了,并且 child 已经被重新parent 编辑为 init (pid 1).

真正的问题是 child 打印完它的消息后,它继续执行循环,产生更多的 children,使你的程序变成 fork bomb.