2013-03-30 29 views
2

我想在一位家长中分娩三个孩子的过程。 和下面是我的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 

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

谢谢大家。 :)

回答

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

是的!这是正确的。非常感谢 : ) – jaychung

0

这里有两个问题:

  • 孩子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 
+0

谢谢你的教学。现在我知道了。 :) – jaychung

0

从最后一个条件将您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; 

    } 

这样父母会继续上厕所p,孩子们将终止而不是循环。

+0

我明白了!!!谢谢^ __^ – jaychung

相关问题