program to generate and print Fibonacci series

0
2
  • Parent program should create a child and distribute the task of generating Fibonacci no to its child.
  • The code for generating Fibonacci no. should reside in different program.
  • Child should write the generated Fibonacci sequence to a shared memory.
  • Parent process has to print by retrieving the Fibonacci sequence from the shared memory. i) Implement the above using shmget and shmat Note: Shared object should be removed at the end in the program
/////////////////////////////////////parent///////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <string.h>

void main(){
	int shmid, n;
	int *shared_memory;
	
	shmid = shmget((key_t)110011, 1024, 0666|IPC_CREAT);
	shared_memory = (int*)shmat(shmid,NULL,0);
	
	printf("Enter n>> ");
	scanf("%d",&n);
	char nstr[20];
	sprintf(nstr, "%d", n);
	
	if (fork()==0){
		execlp("./child", "child", nstr, NULL);
	}
	else{
		wait(NULL);
		
		for(int i=0;i<n;i++){
			printf("%d ",shared_memory[i]);
		}
		printf("\n");
		
		shmdt(shared_memory);
	
	}
}
///////////////////////////////////////////////Child//////////////////////////////////////////////////
//Compile this program with arguments -> ( -o child )

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/wait.h>

void main(int argc, char* argv[]){

	int shmid, n;
	int buffer[25];
	int *shared_memory;
	n = atoi(argv[1]);
	
	shmid = shmget((key_t)110011, 1024, 0666);
	shared_memory = (int*)shmat(shmid,NULL,0);
		
	buffer[0] = 0;
	buffer[1] = 1;
	for(int i=2; i<n;i++){
		buffer[i] = buffer[i-1] + buffer[i-2];
	}
	
	for(int i=0;i<n;i++)
		shared_memory[i]=buffer[i];
}