Program to generate and print N ODD numbers 

0
1
  • Parent program should create a child and distribute the task of generating odd numbers to its child.
  • The code for generating odd numbers should reside in different program.
  • Child should write the generated odd numbers to a shared memory.
  • Parent process has to print the odd numbers by retrieving 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/types.h>
#include <sys/wait.h>
#include <sys/shm.h>

void main(){
	
	int n,i,shmid;
	int *shared_memory;
	
	printf("Enter n>> ");
	scanf("%d", &n);
	char nstr[20];
	sprintf(nstr, "%d", n);
	
	shmid = shmget((key_t)110011,1024,0666|IPC_CREAT);
	shared_memory = (int*)shmat(shmid,NULL,0);
	
	if (fork()==0){
		execlp("./child","child",nstr,NULL);
	}
	else{
		wait(NULL);
		for(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/types.h>
#include <sys/wait.h>
#include <sys/shm.h>

void main(int argc, char* argv[]){
	int n,i,shmid;
	int *shared_memory;
	
	n = atoi(argv[1]);
	
	shmid = shmget((key_t)110011,1024,0666);
	shared_memory = (int*)shmat(shmid,NULL,0);

	int j=0;
	for(i=1;i<2*n;i++){
		if (i%2!=0){
			shared_memory[j] = i;
			j++;
		}
	}
	
}