C ++使用fork()生成2个子节点

时间:2017-03-02 07:09:41

标签: c++ operating-system fork

请您查看我的代码,这是一个C ++程序,可以生成一个父母的2个孩子。用户应输入num值以创建进程链。问题是每个父母的孩子的pid是一样的,我怎么能让他们与众不同?

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


using namespace std;

int main()
{
    cout<<"Please enter a number of process "<<endl;
    int num;
    cin>>num;

    int j;
    for(j=0; j<num; j++)
    {

        pid_t pid;

        pid = fork();

        if(pid < 0)
        {
            cout<<"Error"<<endl;
            exit(1);
        } else if (pid > 0) {
            cout << "Parent " << getpid() << endl;
            exit(0); 
        } 
        else  {
            int i;
            for(i = 0; i < 2; i++) {
                wait(NULL);
                cout << " Child " << getpid() << endl;

            }
        }
    }

    return 0;
}

输出

Parent 27130
 Child 27322
 Child 27322
Parent 27322
 Child 31901
 Child 31901
Parent 31901
 Child 20453
Child 20453

2 个答案:

答案 0 :(得分:0)

您的代码存在多个问题。
else中,这是子进程。当这个过程没有子进程时,你是waiting ...所以它会跳过它并打印它的pid两次!。

这与fork无关,而是与你的for循环有关。 for(i = 0; i < 2; i++)

修改
如果您只想打印一次,只需删除for循环,它只会打印一次。
如果你只想让父两个fork两个子进程,那么流应该是这样的:

pid_t pid2;
cout << "Parent " << getpid() << endl;
pid_t pid = fork();
if (pid == -1) { // handle error }
else if (pid == 0) { // child process 
    cout << " Child " << getpid() << endl;
} 
else { // parent process
      pid2 = fork();
      if (pid2 == -1) { //handle error }
      else if (pid2 == 0) { //child process 
          cout << " Child " << getpid() << endl;
} 

答案 1 :(得分:0)

根据Tony Tannous的评论,我认为你需要的是:

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

using namespace std;

void childFun()
{
   int i;
   for(i = 0; i < 2; i++) {

      cout << " Child " << getpid() << endl;
   }
}

int main(){

   cout<<"Please enter a number of process "<<endl;
   int num;
   cin>>num;

   int j;
   for(j=0; j<num; j++)
   {
      pid_t pid = fork();

      if(pid < 0) {
         cout<<"Error"<<endl;
         exit(1);
      } else if (pid > 0) {
         cout << "Parent " << getpid() << endl;
         // Continue on to create next child.
         // Don't exit.
         // exit(0); 
      } else  {
         // Do whatever the child needs to do.
         childFun();

         // Exit the child process after that
         exit(0);
      }
   }

   return 0;
}