Fibonacci using fork () in a child process

I wrote the code below for homework. When I run it on Xcode in OSX, after the sentence "Enter the Fibonacci sequence number:", I enter the number 2 times. Why 2 and only 1 scanf .

Code:

 #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; } 
+4
source share
2 answers

You have a space after %d in your scanf. Try scanf("%d", &i); .

+5
source

When you call fork() , both processes get their own copies of stdout , and the message in the buffer is duplicated. Therefore, to solve this problem, you will need to hide stdout just before the fork.

Solution: Write fflush(stdout) immediately after printf("Enter the number of a Fibonacci Sequence:\n")

0
source

All Articles