Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如果要为同一个父级创建多个子级,fork()如何工作?_C_Fork_Parent_Child Process - Fatal编程技术网

C 如果要为同一个父级创建多个子级,fork()如何工作?

C 如果要为同一个父级创建多个子级,fork()如何工作?,c,fork,parent,child-process,C,Fork,Parent,Child Process,我还没有真正弄明白fork()实际上是如何工作的。我想知道如何创建一个包含多个子进程的父进程 fork(); fork(); 这会返回一个有两个孩子的父母吗?第一个fork()=parent+child,第二个fork()=idk?它将总共创建4个进程 主进程将用第一个fork()派生一个进程 在第二个fork(),之前的两个进程都将创建新进程,使2x2=4fork()拆分当前程序,生成两个相同的副本-区别仅在于fork()的返回代码 因此,如果您fork()两次: fork(); for

我还没有真正弄明白fork()实际上是如何工作的。我想知道如何创建一个包含多个子进程的父进程

fork();
fork();

这会返回一个有两个孩子的父母吗?第一个fork()=parent+child,第二个fork()=idk?

它将总共创建4个进程

主进程将用第一个
fork()派生一个进程

在第二个
fork()
,之前的两个进程都将创建新进程,使
2x2=4

fork()
拆分当前程序,生成两个相同的副本-区别仅在于
fork()的返回代码

因此,如果您
fork()
两次:

 fork();
 fork();
然后将发生的事情是-第一个fork将
parent
拆分为
parent+child

第二个叉子会把两个叉子分开,因为孩子从同一个点开始。给你:

parent 
+ - child
  + - child
+ - child
为了避免这种情况,您需要检查
fork()
的返回代码,并使用返回代码确定您是否仍在
父级中。这不一定是坏事,但你需要意识到它会发生,并确保你适当地处理信号、返回码、等待等。因此,通常您只需要从父级执行
分叉操作

fork()
将子进程的进程id返回给父进程,或将零返回给子进程。因此:

if( fork() != 0)  // create a child
{
    // we are in parent
    if( fork() != 0)  // create another child
    {
        // we are in parent
    }
    else
    {
        // we are in the 2nd child
    }
}
else
{
    // we are in the 1st child
}
您还可以从子进程创建子进程:

if( fork() != 0)  // create a child
{
    // we are in parent
}
else
{
    // we are in the child
    if( fork() != 0)  // create a grand-child
    {
        // we are in a first child
    }
    else
    {
        // we are in the grand-child
    }
}
要创建5个子对象,请执行以下操作:

// describe the work for 5 children
SomeWorkDescription tab[ 5 ];

int  childCnt;

for( childCnt = 0; childCnt < 5; childCnt ++ )
{
    if( fork() == 0 )
    {
        // we are in a child - take a description
        // of what should be done and go
        doSomeChildWork( tab[childCnt] );

        // it's the parent's loop, children do not iterate here
        break;
    }
    // else we are in a parent - continue forking
}
//描述5个孩子的工作
SomeWorkDescription页签[5];
国际儿童基金会;
对于(childCnt=0;childCnt<5;childCnt++)
{
如果(fork()==0)
{
//我们是一个孩子——描述一下
//该做什么,该走什么
doSomeChildWork(选项卡[childCnt]);
//这是父循环,子循环不在此迭代
打破
}
//否则,我们将处于父级-继续分叉
}

Read给出了一个解决方案,但没有直接回答OP发布的代码问题。是的,它回答了。问题是“我想知道如何创建一个包含多个子进程的父进程?”该示例演示了s/he如何创建父进程。