Wednesday, January 19, 2011

IPC pgm using shard memory and pipes-1

//in this program a parent process reads no.s in shared memory and its child sorts it and //child's child performs binary search on it
#include"stdio.h"
#include"unistd.h"
#include"sys/types.h"
#include"sys/shm.h"
#include"sys/sem.h"
#include"sys/wait.h"
#include"sys/ipc.h"
#define MUTEX 0
////////////////////////
int bsearch(int key,int s,int l,int* temp)
{ if(s>=l)
return -1;
int mid=(s+l)/2;
if(key==temp[mid])
return mid;

else if(key>temp[mid])
{ s=mid+1;
bsearch(key,s,l,temp);
}
else if(key { l=mid-1;
bsearch(key,s,l,temp);
}
}
/////////////////////
void initsem(int sem_id,int sem_num,int value)
{
union semum
{ int val;
struct semid_ds* buf;
unsigned short * array;
}argument;
argument.val=value;
semctl(sem_id,sem_num,SETVAL,argument);
}
//////////////////////////

void up(int sem_id,int sem_num,struct sembuf * semaphore)
{
semaphore->sem_num=sem_num;
semaphore->sem_op=1;
semaphore->sem_flg=0;
semop(sem_id,semaphore,1);
}
//////////////////////////////////////
void down(int sem_id,int sem_num,struct sembuf * semaphore)
{
semaphore->sem_num=sem_num;
semaphore->sem_op=-1;
semaphore->sem_flg=0;
semop(sem_id,semaphore,1);
}
//////////////////////////////////////

void main()
{ key_t shm_key=1234,sem_key=3456;pid_t child1,child2;
int shm_id,sem_id;int size,i,j,pos,key,n,t;int *shm;int temp[20],temp1[20];
int pd[2],st;
struct sembuf semaphore;
printf("\n enter the no of no.s ");
scanf("%d",&n);
size=n*sizeof(int);
st=pipe(pd);
if(st==-1)
printf("\n unable to create pipe");
shm_id=shmget(shm_key,size,IPC_CREAT|0666);
shm=shmat(shm_id,NULL,0);
sem_id=semget(sem_key,1,IPC_CREAT|0666);
initsem(sem_id,MUTEX,1);
child1=fork();
if(child1==0)
{ //child 1 creates its child
child2=fork();
if(child2==0)
{//child2
sleep(n*6);
close(pd[1]);

printf("\n child 2 reads");
down(sem_id,MUTEX,&semaphore);
read(pd[0],temp1,sizeof(temp1));
up(sem_id,MUTEX,&semaphore);
for(i=0;i { printf("\nch2- %d\n",temp1[i]);
}
printf("\n enter the key to be searched");
scanf("%d",&key);
pos=-1;

pos=bsearch(key,0,n,temp1);
if(pos!=-1)
{ printf("\nkey found at position %d",pos);
}
else
printf("\nkey not found\n");


}//inner if
else
{ //child 1
sleep(n*3);close(pd[0]);
printf("\n child 1 reads");
down(sem_id,MUTEX,&semaphore);
for(i=0;i {
for(j=i+1;j { if(shm[i]>shm[j])
{ t=shm[i];
shm[i]=shm[j];
shm[j]=t;
}
}
}
printf("\n the sorted no.s are\n");
for(i=0;i { temp[i]=shm[i];
printf("\nch1- %d",shm[i]);
}

write(pd[1],temp,sizeof(temp));
up(sem_id,MUTEX,&semaphore);

waitpid(child2,NULL,0);
}//inner else

}//end of if
else
{//parent
down(sem_id,MUTEX,&semaphore);
printf("\n enter no.s\n ");
for(i=0;i { printf("\n no. %d ",i+1);
scanf("%d",&shm[i]);
}
up(sem_id,MUTEX,&semaphore);
waitpid(child1,NULL,0);
}//end of else

}

No comments:

Post a Comment