【问题标题】:fork mulitple child in one parent在一个父母中分叉多个孩子
【发布时间】:2013-03-30 08:59:18
【问题描述】:

我想在一个父进程中分叉三个子进程。 以下是我的 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

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

谢谢大家。 :)

【问题讨论】:

    标签: c++ fork


    【解决方案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;
        }
    }
    

    【讨论】:

      【解决方案2】:

      有两个问题:

      • 子 0 和 1 继续 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
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-13
          • 2012-01-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多