2016-09-15 33 views
1

我試圖在C.處理器農場我先開口消息隊列,事後儘量使工作進程:(注意NROF_WORKERS 5)只有1名兒童在5個叉(C)

static void 
makechildren (void) { 
    // Only the parent should fork. Any children created will become workers. 
    pid_t processID; 
    pid_t farmerPID = getpid(); // To identify who the farmer is 

    // Loop creating processes, indexed by NROF_WORKERS 
    int i = 0; 
    while (i < NROF_WORKERS){ 
     if (getpid() == farmerPID){ 
      i++; 
      printf ("Parent is creating a child!%d\n", getpid()); 
      processID = fork(); 
     } 
    } 

    if (processID < 0){ 
     perror("fork() failed"); 
     exit(1); 
    } 
    else { 
    // If parent, start farming 
     if (processID == farmerPID) { 
      printf("Parent reporting in!%d\n"); 
     } 
    // If child, become a worker 
     if (processID == 0) { 
      printf("Child reporting in!%d\n", getpid()); 
      join(); 
     } 
    } 
} 

正如您所看到的,我希望父母在任何時候創建孩子時都會報告,之後我希望父母和所有孩子都能報告。然而,這是我得到的:

Parent is creating a child!11909 
Parent is creating a child!11909 
Parent is creating a child!11909 
Parent is creating a child!11909 
Parent is creating a child!11909 
Child reporting in!11914 

現在,我注意到在11909的差異,11914是5。所以我的問題:是對其他進程產生的?如果是這樣,他們怎麼不報告?如果不是,我做錯了什麼?另外,家長根本沒有報告,這是如何引起的?

回答

2

所有的孩子都創建,但將永遠循環下去,在while循環,爲i只父遞增:

int i = 0; 
while (i < NROF_WORKERS){ 
    if (getpid() == farmerPID){  
     i++;    // <---- This is happening for the parent process only. 
     printf ("Parent is creating a child!%d\n", getpid()); 
     processID = fork(); 
    } 
} 

終止獨生子女是最後一個,爲此i等於NROF_WORKERS

而且父「未報告」以來,processID要檢查等於父PID是永遠等於它,因爲它是等於最近fork結果,即最近創建的子PID:

......... 
processID = fork(); 
......... 
......... 
if (processID == farmerPID) { 
      printf("Parent reporting in!%d\n"); 
} 
0

您總是打印farmerPid!但是,隨着信息打印5次,將有效地創建5個流程:

while (i < NROF_WORKERS){ 
    if (getpid() == farmerPID){ 
     i++; 
     printf ("Parent is creating a child!%d\n", getpid()); 
     processID = fork(); 
    } 
} 

如果你要打印的孩子的PID那麼你的代碼必須使得父母與孩子之間的差異,如:

while (i < NROF_WORKERS){ 
    if (getpid() == farmerPID){ 
     i++; 
     printf ("Parent is creating a child!\n"); 
     processID = fork(); 
     if (processID==0) { // child 
      printf("I am the child %d\n",getpid()); 
     } else { // parent 
      printf("Parent just created child %d\n",processID); 
     } 
    } 
}