Sign in to follow this  
Followers 0
asha91

Fibonacci series in C

2 posts in this topic

This function accepts the number of terms in the Fibonacci sequence in the child process, creates an array, and redirects the output to the parent via pipe. Parent must wait till the child develops the Fibonacci series. The received text always displays -1, although the transmitted text displays the number of entered numbers *4, which is acceptable.

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

int* fibo(int n)
{
    int* a=(int*)malloc(n*sizeof(int));
    *(a+0)=0;
    *(a+1)=1;
    int i;
    for(i=0;i<n-2;i++)
    {
        *(a+i+2)=*(a+i)+(*(a+i+1));
    }
    return a;
    }


    int main()
    {
        int* fib;
        int fd[2];
        pid_t childpid;
        int n,nb;

        int k=pipe(fd);
        if(k==-1)
        {
        printf("Pipe failed");
        return 0;
    }

    childpid=fork();
    if(childpid == 0) 
    {
        printf("Enter no. of fibonacci numbers");
        scanf("%d",&n);
        fib=fibo(n);
        close(fd[0]);
        nb=(fd[1],fib,n*sizeof(int));
        printf("Sent string: %d \n",nb);
        exit(0);
    }
    else
    {
        wait();
        close(fd[1]);
        nb= read(fd[0],fib,n*sizeof(int));
        printf("Received string: %d ",nb);
    }
    return 0;
}

 

0

Share this post


Link to post
Share on other sites

Sorry for the delay, i believe n is uninitialized in the parent process.  (also i assume the fifth line in the childpid == 0 clause is a typo and is actually nb=write(fd[1],fib,n*sizeof(int)) in your code.)

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Recently Browsing   0 members

    No registered users viewing this page.