在一个父母中分叉多个孩子

时间:2013-03-30 08:59:18

标签: c++ fork

我想在一个父级中分叉三个子进程。 以下是我的C ++代码:

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

using namespace std;

int main()
{
    pid_t pid;
    for (int i = 0; i < 3; i++)
    {
        pid = fork();

        if (pid < 0)
        {
            cout << "Fork Error";
            return -1;
        }
        else if (pid == 0)
            cout << "Child " << getpid() << endl;
        else
        {
            wait(NULL);
            cout << "Parent " << getpid() << endl;
            return 0;
        }
    }
}

现在我的输出是:

Child 27463
Child 27464
Child 27465
Parent 27464
Parent 27463
Parent 27462

如何修改程序以获得如下输出?

Child 27463
Child 27464
Child 27465
Parent 27462

我的意思是这三个孩子需要属于同一个父母,有人可以给我一些建议吗?

谢谢大家。 :)

3 个答案:

答案 0 :(得分:1)

您应该退出子进程的执行。否则,他们继续分叉

pid_t pid;
for(i = 0; i < 3; i++) {
    pid = fork();
    if(pid < 0) {
        printf("Error");
        exit(1);
    } else if (pid == 0) {
        cout << "Child " << getpid() << endl;
        exit(0); 
    } else  {
        wait(NULL);
        cout << "Parent " << getpid() << endl;
    }
}

答案 1 :(得分:0)

有两个问题:

  • 儿童零和一个继续for循环,产生进一步的过程;
  • “父”分支终止而不是继续循环。

以下将产生您想要的输出:

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

using namespace std;

int main()
{
    pid_t pid;
    for (int i = 0; i < 3; i++)
    {
        pid = fork();

        if (pid < 0)
        {
            cout << "Fork Error";
            return -1;
        }
        else if (pid == 0) {
            cout << "Child " << getpid() << endl;
            return 0;
        } else {
            wait(NULL);
            if (i == 2) {
                cout << "Parent " << getpid() << endl;
            }
        }
    }
}

当我运行它时,我得到了

Child 4490
Child 4491
Child 4492
Parent 4489

答案 2 :(得分:0)

return 0从最后一个条件移到中间条件:

    if (pid < 0)
    {
        cout << "Fork Error";
        return -1;
    }
    else if (pid == 0) {
        cout << "Child " << getpid() << endl;
        return 0;
    }
    else
    {
        wait(NULL);
        cout << "Parent " << getpid() << endl;

    }

这样父级将继续循环,子级将终止而不是循环。