2014-04-19 35 views
0

我想用vfork()編寫一個程序,父母創建n個子女,我想插入帶參數的兒子數。然後,我要總結兒子的數量,例如:用vfork和子女總數()

./sum 4 
The sum of the child: 10 
The sum of the parent: 10 

(1 + 2 + 3 + 4)

這是我來到了小的代碼,但我得到無限循環。

int n = atoi(argv[1]); 
int i = 1; 
pid_t pid; 
int sumchild = 0; 
int sumparent = 0; 

    while(i <= n){ 
     pid = vfork(); 
     if(pid == 0){ 
      sumchild = sumchild + i;   
     } 

     i++; 
    } 
    printf("The sum of the child: %i ", sumchild); 

    sumparent = (1 + n) * (n/2); 
    printf("The sum of the parent: %i \n", sumparent); 

聽說你不需要wait()fork(),但我不知道爲什麼我在這裏得到無限循環。

我應該如何使用vfork()? 我甚至寫了代碼,還是犯了一些錯誤?

回答

1

以下代碼

pid = vfork(); 
    if(pid == 0){ 
     sumchild = sumchild + i; 

將導致未定義的行爲,根據vfork

該了vfork()函數具有作爲叉相同的效果(2),不同之處在於該行爲是未定義如果由vfork()創建的進程修改除用於存儲vfork()的返回值或從調用vfork()的函數返回的類型爲pid_t的變量以外的任何數據,或者在成功調用任何其他函數調用_exit(2)或exec(3)系列函數之一。