如何使用fork()来创建只有2子进程? [英] How to use Fork() to create only 2 child processes?

查看:210
本文介绍了如何使用fork()来创建只有2子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习一些C和留学期间的岔路口,等待函数我得到了一个意外的输出。至少对我来说。

有没有方法来创建只有2从父子进程?

下面我code:

 的#include< SYS / types.h中>
#包括LT&;&stdio.h中GT;
#包括LT&;&unistd.h中GT;
#包括LT&; SYS / wait.h>诠释的main()
{
    / *创建管道* /
    INT FD [2];
    管(FD);    将为pid_t PID;
    将为pid_t PIDB;
    PID =叉();
    PIDB =叉();    如果(PID℃,)
    {
        的printf(叉失败\\ n);
        返回-1;
    }
    否则,如果(PID == 0)
    {
        //的printf(我的孩子\\ n);
    }
    其他
    {
        //的printf(我父\\ n);
    }    的printf(我的pid%d个\\ N,GETPID());    返回0;
}

和这里是我的输出:

 我的pid 6763
我的pid 6765
我的pid 6764
我的pid 6766

请,忽略管道的一部分,我还没有得到那么远呢。我只是想,所以我希望3只创建2子进程我PID ......只输出1父,我将等待2子进程,将通过管道进行通信。

让我知道如果你看到我的错误。


解决方案

  PID =叉(); #1
PIDB =叉(); #2

让我们假设父进程ID为100,第一个叉创建另一个进程101.现在,这两个100安培; 101继续#1之后​​执行的,所以他们执行第二个叉。 PID达到100#2创建另一个进程的pid 102到达101#2创建另一个进程103.所以我们最终有4个过程。

你应该做的就是这样的事情。

 如果(叉())​​#父
    如果(叉())​​#parent
    其他#的child2
其他#child1

I'm starting to learn some C and while studying the fork, wait functions I got to a unexpected output. At least for me.

Is there any way to create only 2 child processes from the parent?

Here my code:

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

And Here is my output:

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

Please, ignore the pipe part, I haven't gotten that far yet. I'm just trying to create only 2 child processes so I expect 3 "I'm pid ..." outputs only 1 for the parent which I will make wait and 2 child processes that will communicate through a pipe.

Let me know if you see where my error is.

解决方案

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

Let us assume the parent process id is 100, the first fork creates another process 101. Now both 100 & 101 continue execution after #1, so they execute second fork. pid 100 reaches #2 creating another process 102. pid 101 reaches #2 creating another process 103. So we end up with 4 processes.

What you should do is something like this.

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

这篇关于如何使用fork()来创建只有2子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆