如何通过子进程创建三个子进程?

问题描述 投票:0回答:2

我想从主流程(P0)的子流程中创建三个子流程。所以像->

P0 -> P1 ->P2  
             ->P3
             ->P4

但是,每当我运行它时,我都会得到(对于进程P2,P3,P4)主进程的ppid(ppid = 1)。

我正在使用fork()系统调用来创建子代,并且该程序的实现在C中。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int i, pid1, pid2;
    pid1 = fork();
    printf("Pid1 pid -> %d ppid -> %d\n",getpid(),getppid());
    if(pid1 != 0)
    {
        pid2 = fork();
        printf("Pid2 pid -> %d ppid -> %d\n",getpid(),getppid());
        if(pid2 == 0)
        {
            for(i=2; i<5; i++)
            {
                //if(fork()==0)
                //{
                    printf("Child %d pid -> %d Parent -> %d\n",i+1,getpid(),getppid());
                //}
                exit(0);
            }
        }
        else 
        {
            printf("Pid2 father process \n");
        }  
    }
    else 
    {
        printf("Pid1 child process\n");

    }
}
c parallel-processing fork
2个回答
0
投票

警告,以

pid1 = fork();
printf("Pid1 pid -> %d ppid -> %d\n",getpid(),getppid());

<< [printf在P0和P1中均已完成,您必须先检查pid1才能确定自己的位置

...待续

0
投票
您想要以下内容:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { int i, pid1, pid2; pid1 = fork(); printf("Pid1 pid -> %d ppid -> %d\n",getpid(),getppid()); // parent if(pid1 != 0) { pid2 = fork(); printf("Pid2 pid -> %d ppid -> %d\n",getpid(),getppid()); if(pid2 == 0) { for(i=2; i<5; i++) { if(fork()==0) { printf("Child %d pid -> %d Parent -> %d\n",i+1,getpid(),getppid()); // some functionality here exit(0); } } exit(0); } else { printf("Pid2 father process \n"); } } else { printf("Pid1 child process\n"); } }

在我的机器中提供以下输出:

Pid1 pid -> 17764 ppid -> 32242 Pid1 pid -> 17765 ppid -> 17764 Pid1 child process Pid2 pid -> 17764 ppid -> 32242 Pid2 father process Pid2 pid -> 17766 ppid -> 17764 Child 3 pid -> 17767 Parent -> 17766 Child 4 pid -> 17768 Parent -> 17766 Child 5 pid -> 17769 Parent -> 17766

因此,具有以下层次结构:

父母(pid:17764)C1(17765)-> C2-> 17666C3-> 17767C4-> 17768C5-> 17769

© www.soinside.com 2019 - 2024. All rights reserved.