2017-03-02 37 views
0

请您检查一下我的代码,它是一个C++程序,用于生成一个父代的2个子代。用户应该输入num值来创建一个过程链。问题是每个家长的孩子pid是一样的,我怎样才能让他们与众不同?使用fork()生成2个孩子的C++

#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 
+0

这是我不清楚预期的输出是什么。 –

+0

@RSahu他希望它只打印一次。他想要查看父级创建的两个子进程的pid。 –

回答

0

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

这与fork无关,但与您的for循环。 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; 
} 
0

基于由托尼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; 
} 
+0

你的回答有点问题,首先,他想打印他希望产卵的两个过程的PID,然后第一个孩子在他的代码中创建另一个孩子,这是另一个问题,尽管你修复了这个问题,但它仍然会打印孩子处理pid两次。并且不保证父母将首先打印其pid ...子进程可能首先运行。看我的答案。 –

+0

@TonyTannous,我希望OP能够清楚他们可以修改'childFun'中的代码来做任何他们想做的事情。可以很容易地控制孩子PID打印一次还是打印十次。重新打印PID的顺序,在第一个分支之前很容易控制父进程的输出,但在此之后,程序员可以做的很少。 –

+0

谢谢你的帮助。 – user7548941

相关问题