【问题标题】:C++ using fork() to generate 2 childrenC++ 使用 fork() 生成 2 个孩子
【发布时间】:2026-02-02 16:45:01
【问题描述】:

请检查我的代码,它是一个 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

【问题讨论】:

  • 我不清楚预期的输出是什么。
  • @RSahu 他希望它只打印一次。他想查看父进程创建的两个子进程的 pid。

标签: c++ operating-system fork


【解决方案1】:

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

这与 fork 无关,而是与您的 for 循环有关。 for(i = 0; i &lt; 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;
} 

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 您的回答有点问题,首先,他想打印他希望生成的两个进程的 pid,然后第一个孩子在他的代码中创建另一个孩子,这是另一个问题,虽然你解决了这个问题,它仍然会打印两次子进程pid。并且不能保证父进程会首先打印它的 pid ......子进程可能会首先运行。看我的回答。
    • @TonyTannous,我希望 OP 清楚他们可以修改childFun 中的代码以做任何他们想做的事情。子PID是打印一次还是10次都可以轻松控制。重新打印 PID 的顺序,在第一次 fork 之前很容易控制父进程的输出,但在此之后,程序员几乎无能为力。
    • 感谢您的帮助。