2010-11-22 80 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")