Fibonacci series in C

For discussions about programming, and for programming questions and advice


Moderator: Forum moderators

Post Reply
KalamyQ
Posts: 16
Joined: Wed Jul 13, 2022 10:59 am
Has thanked: 3 times

Fibonacci series in C

Post by KalamyQ »

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.

Code: Select all

#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;
}
Burunduk
Posts: 245
Joined: Thu Jun 16, 2022 6:16 pm
Has thanked: 6 times
Been thanked: 123 times

Re: Fibonacci series in C

Post by Burunduk »

Your example is messed up completely. Even write() function's name is missing. But if you've copied it for yourself more carefully, look at the n variable used to calculate the number of bytes to read. It's set in the block executed by a child process and used uninitialized in the block executed by a parent. No surprise that read() fails.

KalamyQ
Posts: 16
Joined: Wed Jul 13, 2022 10:59 am
Has thanked: 3 times

Re: Fibonacci series in C

Post by KalamyQ »

yes i am kinda bad at this and thank you for your help

Post Reply

Return to “Programming”