#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/sem.h>
///#include <time.h>
#include <string.h>
#include <sys/types.h>

#define SHM_KEY 99
#define SEM_KEY 111


init_sem(int semid,int semnum,int val)
{
    union semun{
	int val;
	struct semid_ds *buf;
	unsigned short *array;
    }initval;
    initval.val=val;
    if(semctl(semid,semnum,SETVAL,initval)==-1)
    {
	perror("semctl");
	exit(1);
    }
}

int get_sem(int semid,int semnum)
{
    int val;
    if((val=semctl(semid,semnum,SETVAL))==-1)
    {
	perror("semctl");
	exit(1);
    }
    return val;
}


lockforread(int semid)
{
    struct sembuf action[2];
    action[0].sem_num=1;
    action[0].sem_flg=SEM_UNDO;
    action[0].sem_op=0; 
    action[1].sem_num=0;
    action[1].sem_flg=SEM_UNDO;
    action[1].sem_op=+1;
    if(semop(semid,action,2)==-1)
    {
	perror("semop");
	exit(1);
    }
}

unlockafterread(int semid)
{
    struct sembuf action[1];
    action[0].sem_num=0;
    action[0].sem_flg=SEM_UNDO;
    action[0].sem_op=-1;
    if(semop(semid,action,1)==-1)
    {
	perror("semop");
	exit(1);
    }

}

main()
{
    int seg_id,semid;
    char *mem_ptr;
    
    seg_id=shmget(SHM_KEY,100,0777);
    if(seg_id==-1)
    {
	perror("shmget");
	exit(1);
    }
    mem_ptr=shmat(seg_id,NULL,0);
    if(mem_ptr==NULL)
    {
	perror("shmat");
	exit(1);
    }

    semid=semget(SEM_KEY,2,0);
    if(semid==-1)
    {
	perror("semget");
	exit(1);
    }
  //  init_sem(semid,0,0);
  //  init_sem(semid,1,0);

    lockforread(semid);
    printf("*************************************\n");
    printf("read value=%d,write value=%d\n",get_sem(semid,0),get_sem(semid,1));
    printf("*************************************\n");
    printf("The time is:%s\n",mem_ptr);
    unlockafterread(semid);
    printf("*************************************\n");
    printf("read value=%d,write value=%d\n",get_sem(semid,0),get_sem(semid,1));
    printf("*************************************\n");
 
    shmdt(mem_ptr);
}
