信号量

来源:互联网 发布:中国网络诗歌网高研班 编辑:程序博客网 时间:2024/06/02 22:05
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/sem.h>//包含信号量定义的头文件
//联合类型semun定义
union semun{
int val;
struct semid_ds *buf;
unsigned short *array;
};
//函数声明
//函数:设置信号量的值
static int set_semvalue(int);
//函数:删除信号量
static void del_semvalue(void);
//函数:信号量P操作
static int semaphore_p(void);
//函数:信号量V操作
static int semaphore_v(void);
static int get_semvalue(void);
static int sem_id;//信号量ID
int main(int argc,char *argv[])
{
int i,val;
//创建一个新的信号量或者是取得一个已有信号量的键
sem_id = semget((key_t)1234,1,0666 | IPC_CREAT);
val=get_semvalue();
printf("val=%d\n",val);
set_semvalue(5);
val=get_semvalue();
printf("val2=%d\n",val);
semaphore_p();
val=get_semvalue();
printf("val3=%d\n",val);
//V操作,尝试离开缓冲区
semaphore_v();
val=get_semvalue();
printf("val4=%d\n",val);
printf("\n %d - finished \n",getpid());
}
//函数:设置信号量的值
static int set_semvalue(int val)
{
union semun sem_union;
sem_union.val = val;
if(semctl(sem_id,0,SETVAL,sem_union))
return 0;
return 1;
}
//获取信号量的值
static int get_semvalue(void)
{
int ret=semctl(sem_id,0,GETVAL);
return ret;
}
//函数:删除信号量
static void del_semvalue(void)
{
union semun sem_union;
if(semctl(sem_id,0,IPC_RMID,sem_union))
fprintf(stderr,"Failed to delete semaphore\n");
}
//函数:信号量P操作:对信号量进行减一操作
static int semaphore_p(void)
{
struct sembuf sem_b;
sem_b.sem_num = 0;//信号量编号
sem_b.sem_op = -1;//P操作
sem_b.sem_flg = SEM_UNDO;
if(semop(sem_id,&sem_b,1) == -1)
{
fprintf(stderr,"semaphore_p failed\n");
return 0;
}
return 1;
}
//函数:信号量V操作:对信号量进行加一操作
static int semaphore_v(void)
{
struct sembuf sem_b;
sem_b.sem_num = 0;//信号量编号
sem_b.sem_op = 1;//V操作
sem_b.sem_flg = SEM_UNDO;
if(semop(sem_id,&sem_b,1) == -1)
{
fprintf(stderr,"semaphore_v failed\n");
return 0;
}
return 1;
}

原创粉丝点击