C 使用叉()生成2个孩子

C++ using fork() to generate 2 children

本文关键字:生成 2个 孩子      更新时间:2023-10-16

您是否请检查我的代码,这是一个生成一个父母的孩子的C 程序。用户应输入数值以创建一个过程链。问题是孩子们对每个父母的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

基于托尼·塔尼斯(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;
}

您的代码多个问题。
else中,这是子过程。当此过程没有子进程时,您是waiting ...因此,它只会跳过它并将其PID打印两次!。

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

编辑
如果您只想打印一次,只需删除for循环,它将仅打印一次。
如果您只希望父母两个叉子两个子进程,那么流应该如下:

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