How to write a C program using the fork() system call that generates the Fibonacci sequence in the

Posted by Ellen on Stack Overflow See other posts from Stack Overflow or by Ellen
Published on 2009-04-05T20:54:28Z Indexed on 2010/03/19 8:01 UTC
Read the original article Hit count: 524

Filed under:
|
|
|

The problem I am having is that when say for instance the user enters 7, then the display shows:

0 11 2 3 5 8 13 21 child ends.

I cannot seem to figure out how to fix the 11 and why is it displaying that many numbers in the sequence! Can anyone help?

The number of the sequence will be provided in the command line. For example, if 5 is provided, the first five numbers in the Fibonacci sequence will be output by the child process. Because the parent and child processes have their own copies of the data, it will be necessary for the child to output the sequence. Have the parent invoke the wait() call to wait for the child process to complete before exiting the program. Perform necessary error checking to ensure that a non-negative number is passed on the command line.

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

int main()
{
   int a=0, b=1, n=a+b,i,ii;
   pid_t pid;

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

   if (ii < 0)
      printf("Please enter a non-negative integer!\n");
   else
   {
      pid = fork();
      if (pid == 0)
      {
         printf("Child is producing the Fibonacci Sequence...\n");
         printf("%d %d",a,b);
         for (i=0;i<ii;i++)
         {
            n=a+b;
            printf("%d ", n);
            a=b;
            b=n;
         }
         printf("Child ends\n"); 
      }
      else 
      {
         printf("Parent is waiting for child to complete...\n");
         wait(NULL);
         printf("Parent ends\n");
      }
   }
   return 0;
}

© Stack Overflow or respective owner

Related posts about fibonacci

Related posts about sequence