2016-02-29 112 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()「編輯過程將立即再次叉 - 爲什麼你想有三個。您需要確保您檢查每個分叉調用的結果。

考慮到這一點,您可以重新編寫其他代碼。