如何使用Fork()只创建2个子进程?

时间:2012-06-06 06:13:02

标签: c process fork parent-child wait

我开始学习一些C并且在研究fork时,等待函数我得到了意想不到的输出。至少对于我来说。

有没有办法只从父级创建2个子进程?

这是我的代码:

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main ()
{
    /* Create the pipe */
    int fd [2];
    pipe(fd);

    pid_t pid;
    pid_t pidb;


    pid = fork ();
    pidb = fork ();

    if (pid < 0)
    {
        printf ("Fork Failed\n");
        return -1;
    }
    else if (pid == 0)
    {
        //printf("I'm the child\n");
    }
    else 
    {
        //printf("I'm the parent\n");
    }

    printf("I'm pid %d\n",getpid());

    return 0;
}

这是我的输出:

I'm pid 6763
I'm pid 6765
I'm pid 6764
I'm pid 6766

请忽略管道部分,我还没有那么远。我只是想创建只有2个子进程,所以我希望3“我是pid ......”只输出1个父级,我将等待,2个子进程将通过管道进行通信。

如果你知道我的错误在哪里,请告诉我。

5 个答案:

答案 0 :(得分:31)

pid = fork (); #1
pidb = fork (); #2

让我们假设父进程id为100,第一个fork创建另一个进程101.现在100&amp; 101在#1之后继续执行,因此它们执行第二次分叉。 pid 100到达#2创建另一个进程102.pid 101到达#2创建另一个进程103.所以我们最终得到4个进程。

你应该做的就是这样。

if(fork()) # parent
    if(fork()) #parent
    else # child2
else #child1

答案 1 :(得分:13)

创建流程后,应检查返回值。如果不这样做,则seconde fork()将由父进程和子进程执行,因此您有四个进程。

如果你想创建2个子进程,只需:

if (pid = fork()) {
    if (pid = fork()) {
        ;
    } 
} 

您可以像这样创建n个子进程:

for (i = 0; i < n; ++i) {
    pid = fork();
    if (pid > 0) {   /* I am the parent, create more children */
        continue;
    } else if (pid == 0) { /* I am a child, get to work */
        break;
    } else {
        printf("fork error\n");
        exit(1);
    }
}

答案 2 :(得分:3)

当父级执行fork语句时,会按照您的预期创建子进程。您可以说子进程也执行fork语句但返回0,但父进程返回pid。 fork语句之后的所有代码都由父两者执行。

在您的情况下,发生的事情是第一个fork语句创建了一个子进程。所以现在有一个父母P1和一个孩子C1。

现在P1和C1都遇到第二个fork语句。父母会按照您的预期创建另一个孩子(c2),但即使是孩子,c1也会创建一个子进程(c3)。所以实际上你有P1,C1,C2和C3,这就是你有4个打印语句输出的原因。

考虑这一点的好方法是使用树,每个节点代表一个进程,根节点是最顶层的父节点。

答案 3 :(得分:0)

您可以将值检查为 if(pid <0) 进程创建失败 这告诉子进程创建是否不成功。 如果从父进程使用getpid(),fork将返回子进程的进程id。

答案 4 :(得分:0)

您可以在子进程中创建子进程。这样,您就可以拥有原始父流程的2个副本。

int main (void) {
    pid_t pid, pid2;
    int status;

    pid = fork();

    if (pid == 0) { //child process
        pid2 = fork();
        int status2;

        if (pid2 == 0) { //child of child process
            printf("friends!\n");
        }
        else {
            printf("my ");
            fflush(stdout);
            wait(&status2);
        }
    }
    else { //parent process
        printf("Hello ");
        fflush(stdout);
        wait(&status);
    }

    return 0;
}

这将打印以下内容:

Hello my friends!
相关问题