2015-09-27 36 views
-2

我正在學習一個操作系統類,我們正在學習分叉。我在一個特定的例子中遇到了一些麻煩。我無法在網上找到任何具體解釋我需要的東西。希望這裏有人能幫忙。叉();方法C

#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 

int main() { 
    pid_t pid1, pid2, pid3; 
    pid1=0, pid2=0, pid3=0; 
    pid1= fork(); 
    if(pid1==0){ 
     pid2=fork(); 
     pid3=fork(); 
    } else { 
     pid3=fork(); 
     if(pid3==0) { 
      pid2=fork(); 
     } 
     if((pid1 == 0)&&(pid2 == 0)) 
      printf("Level 1\n"); 
     if(pid1 !=0) 
      printf("Level 2\n"); 
     if(pid2 !=0) 
      printf("Level 3\n"); 
     if(pid3 !=0) 
      printf("Level 4\n"); 
     return 0; 
    } 
} 

任何人都可以解釋這一點嗎?我知道這些流程並行運行,並且不確定哪一個將首先運行。我的問題是瞭解每個分叉後的值。

所以當第一個fork返回時,現在有2個進程,Parent和Child。孩子獲取父母的所有內容。所以父母有pid1,pid2,pid3 = 0對不對?和孩子有相同的?我有一個程序的輸出。如果我剛剛知道第一個叉後發生了什麼,我想我可以解決其餘的問題。

+0

什麼樣的價值觀? PIDs? – Downvoter

+2

1)C不支持_methods_,但只支持_functions_。 2)格式化你的代碼!這是一團糟。 3)'main'的簽名是錯誤的。 4)你沒有找到fork的聯機幫助文件? 5)「先跑步」是什麼意思?想想「平行跑步」意味着什麼。 – Olaf

+1

你問'fork()'返回什麼?請澄清你的問題。 –

回答

2

讓我命名叉:

#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 

int main() { 
    pid_t pid1, pid2, pid3; 
    pid1=0, pid2=0, pid3=0; 
    pid1= fork(); /* A */ 
    if(pid1==0){ 
     pid2=fork(); /* B */ 
     pid3=fork(); /* C */ 
    } else { 
     pid3=fork(); /* D */ 
     if(pid3==0) { 
      pid2=fork(); /* E */ 
     } 
     if((pid1 == 0)&&(pid2 == 0)) 
      printf("Level 1\n"); 
     if(pid1 !=0) 
      printf("Level 2\n"); 
     if(pid2 !=0) 
      printf("Level 3\n"); 
     if(pid3 !=0) 
      printf("Level 4\n"); 
     return 0; 
    } 
} 

然後,執行將是:

----A----D--------- (pid1!=0, pid2==0(as initialized), pid3!=0, print "Level 2" and "Level 4") 
    | | 
    | +----E---- (pid1!=0, pid2!=0, pid3==0, print "Level 2" and "Level 3") 
    |   | 
    |   +---- (pid1!=0, pid2==0, pid3==0, print "Level 2") 
    | 
    +----B----C---- (pid1==0, pid2!=0, pid3!=0, print nothing) 
     | | 
     | +---- (pid1==0, pid2==0, pid3==0, print nothing) 
     | 
     +----C---- (pid1==0, pid2==0, pid3!=0, print nothing) 
       | 
       +---- (pid1==0, pid2==0, pid3==0, print nothing) 
+0

如果您有時間,我可以進一步解釋嗎?http://collabedit.com/hmjyx – Plisken

1

很難猜出哪個部分需要說明,但作爲基本概述,fork()將當前過程複製爲「孩子」。如果呼叫失敗,原始(父級)進程的返回值將等於操作系統中的子進程ID或-1。孩子從代碼中的相同位置開始,返回值爲0,因爲它沒有孩子。

操作系統可以完全控制進程的調度,因此哪一個運行時無法預先猜測,但進程ID可以用來確定子進程的狀態。

該代碼非常抽象,並不真正用於非示例目的。但由於它五次呼叫fork(),它將被主程序調用一次,每個每個由父母和子(總共兩次),每次由父,子和孫(四次)等一次向前。這些應該與發出消息的次數相關。