2010-11-22 2 views
4

나는 숙제를 위해 아래 코드를 작성했습니다. OSX에서 XCode를 실행하면 "피보나치 시퀀스 번호 입력 :"이라는 문장 다음에 2 번 번호를 입력합니다. 왜 2입니까? 1 scanf.자식 프로세스에서 fork()를 사용하는 fibonacci

코드 :

#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의 자체 복사본이 만들어지고 버퍼의 메시지가 복제됩니다. 그래서이 문제를 해결하기 위해서는 포크를 만들기 전에 stdout을 플러시해야합니다.

솔루션 : 쓰기 fflush(stdout) 단지 printf("Enter the number of a Fibonacci Sequence:\n")

관련 문제