#include
#include
#include
#include
#include
#include
#include
#include
#define MUTEX 0
////////////////////
void upsem(int sem_id,int snum,struct sembuf * semaphore)
{ semaphore->sem_num=snum;
semaphore->sem_op=1;
semaphore->sem_flg=0;
semop(sem_id,semaphore,1);
}
///////////////////////////////////
void downsem(int sem_id,int snum,struct sembuf * semaphore)
{ semaphore->sem_num=snum;
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()
{ key_t shm_key=1234,sem_key=5678;
int * shm;int item;int i;
int shm_id,sem_id;
struct sembuf semaphore;
shm_id=shmget(shm_key,sizeof(int),IPC_CREAT|0666);
shm=shmat(shm_id,NULL,0);
sem_id=semget(sem_key,1,IPC_CREAT|0666);
initsem(sem_id,MUTEX,1);
shm[0]=100;
if(fork()==0)
{
while(1)
{ //consumer
sleep(1);
downsem(sem_id,MUTEX,&semaphore);
shm[0]+=4;
printf("\n consumer adds 4 %d ",shm[0]);
upsem(sem_id,MUTEX,&semaphore);
}
}
else
{
while(1)
{//producer)
sleep(1);
downsem(sem_id,MUTEX,&semaphore);
shm[0]-=2 ;
printf("\n producer substracts 2 %d",shm[0]);
upsem(sem_id,MUTEX,&semaphore);
}
}
}//end of main
#include"stdio.h"
ReplyDelete#include"unistd.h"
#include"sys/types.h"
#include"sys/sem.h"
#include"sys/shm.h"
#include"sys/wait.h"
#include"fcntl.h"
#include"sys/ipc.h"
are the header files