program to generate fibbonacci series through pipe system call
This code is to accept no. of terms of fibbonacci series in child process
creating an array and redirecting through pipe the output to parent.
Parent has to wait till child generates fibbonacci series. the recieved
text is always showing -1 whereas the sent text is displaying the number
of inputted integers *4 which is fine.
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
int* fibbo(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 fibbonacci numbers");
scanf("%d",&n);
fib=fibbo(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;
}
No comments:
Post a Comment