2010-11-22 81 views
4

爲了作業目的,我編寫了下面的代碼。當我在OSX中的XCode上運行它時,在輸入「輸入斐波那契數列:」的句子後,我輸入數字2次。爲什麼2和只有1 scanf在子進程中使用fork()的斐波那契

代碼:

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

int main() 

{ 



int a=0, b=1, n=a+b,i; 


printf("Enter the number of a Fibonacci Sequence:\n"); 
scanf("%d ", &i); 

pid_t pid = fork(); 
if (pid == 0) 
{ 
    printf("Child is make the Fibonacci\n"); 
    printf("0 %d ",n); 
    while (i>0) { 
     n=a+b; 
     printf("%d ", n); 
     a=b; 
     b=n; 
     i--; 
     if (i == 0) { 
      printf("\nChild ends\n"); 
     } 
    } 
} 
    else 
    { 
     printf("Parent is waiting for child to complete...\n"); 
     waitpid(pid, NULL, 0); 
     printf("Parent ends\n"); 
    } 
    return 0; 
} 

回答

5

您的scanf函數%d後的空間。嘗試scanf("%d", &i);

0

當您撥打fork()時,兩個進程都會獲得自己的stdout副本,並且緩衝區中的消息會被複制。 所以爲了解決這個問題,你必須在分叉之前刷新標準輸出。

解決方案: 寫fflush(stdout)剛過printf("Enter the number of a Fibonacci Sequence:\n")