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

mim*_*lea 17 c fork process 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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的输出:

I'm pid 6763
I'm pid 6765
I'm pid 6764
I'm pid 6766
Run Code Online (Sandbox Code Playgroud)

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

如果你看到我的错误在哪里,请告诉我.

tux*_*day 31

pid = fork (); #1
pidb = fork (); #2
Run Code Online (Sandbox Code Playgroud)

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

你应该做的是这样的事情.

if(fork()) # parent
    if(fork()) #parent
    else # child2
else #child1
Run Code Online (Sandbox Code Playgroud)

  • 这肯定有效.但是,我建议使用switch语句.fork函数可以返回-1,我们可以在switch语句中使用case -1处理此错误. (5认同)

Fei*_*Xue 13

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

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

if (pid = fork()) {
    if (pid = fork()) {
        ;
    } 
} 
Run Code Online (Sandbox Code Playgroud)

你可以像这样创建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);
    }
}
Run Code Online (Sandbox Code Playgroud)