#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <errno.h>
#include <sys/time.h>
#include <time.h>
//#include "semun.h"
int init_semvalue(void);
void del_semvalue(void);
int semaphore_p(void);
int semaphore_v(void);
static int sem_id;
union semun{
int val;
struct semid_ds *buf;
unsigned short * ary;
};
int init_semvalue(void)
{
union semun sem_union;
sem_union.val = 0;
if(semctl(sem_id, 0, SETVAL, sem_union) == -1) return 0;
return 1;
}
void del_semvalue(void)
{
union semun sem_union;
if(semctl(sem_id, 0, IPC_RMID, sem_union) == -1)
fprintf(stderr, "Failed to delete semaphore\n");
}
int semaphore_p(void)
{
struct sembuf sem_b;
struct timespec timeout={3,0};
sem_b.sem_num = 0;
sem_b.sem_op = -1;
sem_b.sem_flg = SEM_UNDO;
if(semtimedop(sem_id, &sem_b, 1,&timeout) == -1)
{
fprintf(stderr, "semaphore_p failed\n");
return 0;
}
return 1;
}
int semaphore_v(void)
{
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = 1;
sem_b.sem_flg = SEM_UNDO;
if(semop(sem_id, &sem_b, 1) == -1)
{
fprintf(stderr, "semaphore_v failed\n");
return 0;
}
return 1;
}
int main()
{
int i, pause_time;
char op_char = 'O';
srand((unsigned int)getpid());
if( sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT) < 0)
printf("error:%d", errno);
if(!init_semvalue())
{
fprintf(stderr, "Failed to initialize semaphore\n");
exit(EXIT_FAILURE);
}
printf("enter : p, v , Reset,Get value\n");
while(1)
{
// fflush();
scanf("%c",&op_char);
// printf("rece:%c\n",op_char);
switch(op_char)
{
case 'p':
semaphore_p();
printf("ope:%c finish\n",op_char);
break;
case 'v':
semaphore_v();
printf("ope:%c finish\n",op_char);
break;
case 'r':
init_semvalue();
printf("ope:%c finish\n",op_char);
break;
case 'g':
printf("\nnum:%d\n",semctl(sem_id,0,GETVAL));
break;
default:
break;
}
}
}