Wednesday, January 19, 2011

IPC using shared memory-1

//parent stores n no.s in shared memory and child finds max n min
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MUTEX 0
///////////////////
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 initsem(int sem_id,int sem_num,int val)
{ union semum
{ int val;
struct semid_ds* buf;
unsigned short* array;
}argument;
argument.val=val;
semctl(sem_id,sem_num,SETVAL,argument);
}
////////////////////////////////
void main()
{ pid_t childpid;
int i=0,k=0,n;
printf("\n enter the no of nos(<=10)");
scanf("%d",&n);
int size=n*sizeof(int);
struct sembuf semaphore;
key_t shm_key=1234,sem_key=4567;int * shm;
int shm_id,sem_id,j,temp;int big,small;
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);
childpid=fork();
if (childpid==0)
{ //child
sleep(1);
down(sem_id,MUTEX,&semaphore);
printf("\n child process prints \n ");
big=shm[0];
for(i=0;i { if(shm[i]>big)
big=shm[i];
}
small=shm[0];
for(i=0;i { if(shm[i] small=shm[i];
}
for(i=0;i { printf("\n%d\n",shm[i]);
}
printf("\nbiggest:%d smallest:%d\n",big,small);
up(sem_id,MUTEX,&semaphore);
}
else
{//parent
printf("\n parent process takes and sends no.s");

down(sem_id,MUTEX,&semaphore);
k=0;
while(k { printf("\n k=%d,n=%d",k,n);
printf("\nenter no. %d ",k+1);
scanf("%d",&shm[k]);
k++;
}
up(sem_id,MUTEX,&semaphore);
waitpid(childpid,NULL,0);
}
}//end of main

1 comment:

  1. #include"stdio.h"
    #include"sys/types.h"
    #include"unistd.h"
    #include"string.h"
    #include"stdlib.h"
    #include"sys/shm.h"
    #include"sys/ipc.h"
    #include"sys/wait.h"
    #include"sys/sem.h"

    ReplyDelete