#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
union semun
{
int val;
static int semaphore_p(void);
static int semaphore_v(void);
//全局变量:信号量
{
printf("hello world\n");
sem_id = semget((key_t)1234, 1, 0666|IPC_CREAT);
if(sem_id < 0)
{
perror("fail to semget");
exit(1);
}
set_semvalue();
printf("locked\n");
semaphore_p();
sleep(3);
semaphore_v();
printf("unlocked \n");
return 0;
}
static int set_semvalue(void)
{
int ret;
union semun sem_union;
sem_union.val = 1;
ret = semctl(sem_id, 0, SETVAL, sem_union);
if(ret < 0)
{
perror("fail to semctl");
exit(1);
}
return 0;
}
static int semaphore_p(void)
{
struct sembuf sem_buf;
int ret;
sem_buf.sem_num = 0;
sem_buf.sem_op = -1;
sem_buf.sem_flg = SEM_UNDO;
ret = semop(sem_id, &sem_buf, 1);
if(ret < 0)
{
perror("fail to semop P");
}
return 0;
}
static int semaphore_v(void)
{
struct sembuf sem_buf;
int ret;
sem_buf.sem_num = 0;
sem_buf.sem_op = 1;
sem_buf.sem_flg = SEM_UNDO;
ret = semop(sem_id, &sem_buf, 1);
if(ret < 0)
{
perror("fail to semop P");
}
return 0;
}
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdlib.h>
union semun
{
int val;
};
//操作函数:设置,操作P,操作V
static int set_semvalue(void);static int semaphore_p(void);
static int semaphore_v(void);
//全局变量:信号量
static int sem_id;
{
printf("hello world\n");
sem_id = semget((key_t)1234, 1, 0666|IPC_CREAT);
if(sem_id < 0)
{
perror("fail to semget");
exit(1);
}
set_semvalue();
printf("locked\n");
semaphore_p();
sleep(3);
semaphore_v();
printf("unlocked \n");
return 0;
}
static int set_semvalue(void)
{
int ret;
union semun sem_union;
sem_union.val = 1;
ret = semctl(sem_id, 0, SETVAL, sem_union);
if(ret < 0)
{
perror("fail to semctl");
exit(1);
}
return 0;
}
static int semaphore_p(void)
{
struct sembuf sem_buf;
int ret;
sem_buf.sem_num = 0;
sem_buf.sem_op = -1;
sem_buf.sem_flg = SEM_UNDO;
ret = semop(sem_id, &sem_buf, 1);
if(ret < 0)
{
perror("fail to semop P");
}
return 0;
}
static int semaphore_v(void)
{
struct sembuf sem_buf;
int ret;
sem_buf.sem_num = 0;
sem_buf.sem_op = 1;
sem_buf.sem_flg = SEM_UNDO;
ret = semop(sem_id, &sem_buf, 1);
if(ret < 0)
{
perror("fail to semop P");
}
return 0;
}