include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include<sys/types.h>
#include <sys/sem.h>//包含信号量定义的头文件
//联合类型semun定义
union semun{
int val;
struct semid_ds *buf;
unsigned short *array;
};
//函数声明
//函数设置信号量的值
int set_semvalue(int sem_id);
//函数删除信号量
void del_semvalue(int sem_id);
//函数:信号量P操作
int semaphore_p(int sem_id);
//函数:信号量V操作
int semaphore_v(int sem_id);
int main(int argc,char *argv[])
{
int sem_id = semget((key_t)1234,1,0666 | IPC_CREAT);//创建一个新的信号量或者是取得一个已有信号量的键
set_semvalue(sem_id);
pid_t pid;
pid=vfork();
if(pid)
{
if(!semaphore_p(sem_id)) exit(EXIT_FAILURE);
printf("B running!\n");
printf("B %d return value: %d\n",getpid(),pid);
if(!semaphore_v(sem_id)) exit(EXIT_FAILURE);
del_semvalue(sem_id);//删除信号量
}
else
{
if(!semaphore_p(sem_id)); exit(EXIT_FAILURE);
printf("A running...\n");
printf("A %d return value: %d\n",getpid(),pid);
if(!semaphore_v(sem_id)) exit(EXIT_FAILURE);
_exit(0);
}
return 0;
}
//函数设置信号量的值
int set_semvalue(int sem_id)
{
union semun sem_union;
sem_union.val = 1;
if(semctl(sem_id,0,SETVAL,sem_union))
return 0;
return 1;
}
//函数:删除信号量
void del_semvalue(int sem_id)
{
union semun sem_union;
if(semctl(sem_id,0,IPC_RMID,sem_union))
fprintf(stderr,"Failed to delete semaphore\n");
}
//函数:信号量P操作:对信号量进行减一操作
int semaphore_p(int sem_id)
{
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操作:对信号量进行加一操作
int semaphore_v(int sem_id)
{
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;
}