2016-02-29 64 views
-1

这是SOR到目前为止,我已经做了:嵌套fork()的树++

#include <stdio.h> 
#include <stdlib.h> 
int main() 
{ 
    int p1,p2,p3,p4,i; 
    int left,leftPid; 
    int right; 
    left=fork(); 
    right=fork(); 
    for(i=0;i<=2;i++) 
    { 
     if(left==0) 
      printf("\nleft Child Process. Level: %d | myPID: %d | myParent: %d\n",i,getpid(),getppid());  
     else 
      leftPID=left; 
     if (right==0) 
     { 
      printf("\nright Child Process. Level: %d | myPID: %d | myParent: %d\n",i,getpid(),getppid()); 
      right=fork(); 
     } 
     else 
     { 
      printf("\nParent Process. Level %d | My left Child: %d | My right Child: %d | myPID: %d\n",i,leftPID,right,getpid()); 
     } 
    } 
} 

我需要那种输出的:

左子进程。等级:1 | myPID:23560 | myParent:23559

父进程。等级:0 |我的左小孩:23560 |我的右边小孩:23561 | myPID:23559

left Child Process。等级:2 | myPID:23562 | myParent:23561

left Child Process。等级:3 | myPID:23564 | myParent:23563

right Child Process。等级:3 | myPID:23565 | myParent:23563

父进程。等级:2 |我的左小孩:23564 |我的右边小孩:23565 | myPID:23564

父进程。等级:1 |我的左小孩:23562 |我的右边小孩:23563 | myPID:23561

这里是一个树表示什么,我需要:

fork() tree

而且我做的代码是远离我需要什么。我希望有人能帮我解决这个问题。

回答

0

首先要记住的是,当调用fork()时,它下面的代码由child和parent执行。所以你需要通过使用fork()系统调用的返回值来为它们放置两个条件。在你的情况下,在调用left = fork()之后,下一个是right = fork()的语句由parent ,这是对的,但同样的说法也是由左边的孩子执行的,你也不需要!因此在使用left = fork()系统调用之后,为左侧子项和父项放置条件,以便它们可以执行其自己相应的代码路径。你的代码中的另一个错误是,正确的孩子只是反过来是一个正确的孩子,而不是它的孩子。

for(i=0;i<=2;i++) 
{ 
    left=fork(); 
    leftPID=left; 

    if(left==0) //use break statement for left child since we want it to be kicked out and not execute anything! 
    { 
     printf("\nleft Child Process. Level: %d | myPID: %d | myParent:      %d\n",i,getpid(),getppid()) 
     break; // break statement has to used here necessarily or else left child will keep on making left childs 
    }   
    else if(left>0) //this is executed by parent 
    { 
     right=fork(); //parent forks a right child 

     if (right==0) //this is executed by right child 
     { 
      printf("\nright Child Process. Level: %d | myPID: %d | myParent:      %d\n",i,getpid(),getppid()); 
     } 
     else if(right>0) //executed by parent 
     { 
      printf("\nParent Process. Level %d | My left Child: %d | My right Child: %d | myPID: %d\n",i,leftPID,right,getpid()); 
      break; //again use break to kick out parent since now this parent has no work to do and break statement has to used here necessarily or else parent will keep on making childs-left and right 
     } 
    }  
} 
1

这是错误的:

left=fork(); 
right=fork(); 

此代码后,你结束了四个过程 - 因为每个fork()“编辑过程将立即再次叉 - 为什么你想有三个。您需要确保您检查每个分叉调用的结果。

考虑到这一点,您可以重新编写其他代码。