2013-11-22 16 views
1

對於n = 10輸入,我得到一個奇怪的輸出:創建兩個子進程結束的奇總和,甚至系列

pid = 31456 
Sum of Odd series : 25 
pid = 31456 
Sum of Even series : 30 
pid = 31456 

代碼

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

#include <stdlib.h> 

int main() 
{ 
    pid_t child_pid; 
    int i, j, k, n; 
    int sum; 

    //printf("Enter the last number of series : "); 
    scanf("%d", &n); 
    printf("pid = %d\n", getpid()); 

    for(i = 0; i < 2; i++) 
    { 
     child_pid = fork(); 
     if (child_pid < 0) 
     { 
      printf("Failed to create child process . . ."); 
      return 1; 
     } 
     else if (child_pid == 0) 
     { 
      if (i == 0) //find the sum of odd series 
      { 
       sum = 0; 
       for(j = 1; j <= n; j += 2) 
        sum += j; 

       printf("Sum of Odd series : %d\n", sum); 
       exit(0); 
      } 
      else if (i == 1) //find the sum of even series 
      { 
       sum = 0; 
       for(j = 2; j <= n; j += 2) 
        sum += j; 

       printf("Sum of Even series : %d\n", sum); 
       exit(0); 
      } 

     } 
     else 
     { 
      wait(&child_pid); 
     } 
    } 
    return 0; 
} 

Ideone鏈接:ideone.com/TyIkJa

+1

當您使用'fork'時,父進程中的所有數據都被_copied_引入到子進程中:當您在子進程中寫入'sum'時,它不會被傳播回父進程的sum中,如每個子進程將使用它自己的這個變量的版本。 – Nbr44

+0

eww,那麼處理這些問題的正確方法是什麼? –

+0

fork產生了一個過程的副本,所以一旦你退出了孩子,孩子們就會隨着計算出來的數值一起死亡,這些數值是他們本地的。如果你想讀取兒童的值,你必須使用管道或共享內存。 – 2013-11-22 09:02:55

回答

1

你將不得不改變你的代碼如下。

if (childs[i] == 0) 
    { 
     if (i == 0) //find the sum of odd series 
     { 
      for(j = 1; j <= n; j += 2) 
       sum += j; 
      printf("Sum of odd series : %d\n", sum); 
      exit(0); 
     } 
     else if (i == 1) //find the sum of even series 
     { 
      for(k = 2; k <= n; k += 2) 
       sum += k; 
      printf("Sum of even series : %d\n", sum); 
      exit(0); 
     } 

else 
    { 
     wait(&childs[i]); 
    } 

原因是孩子和父母都有他們自己的副本。所以當你結束時,父母仍然有sum = 0,但這些值更新爲child1的「總和」和child2的「總和」。

0

當您分叉進程時,父代和子代初始爲 或多或少的確切副本,包括除fork()的返回碼外的變量值 。

但是關鍵詞有副本。 這兩個過程現在是獨立的,並且變量, 「global」或不是,* 不以任何方式連接 * d。

+0

請您在寫回答時適當地格式化,並在回答時具體說明。 – vishram0709