通信方式--信号量的一系列操作(创建 获取 设置 删除以及PV操作)

时间:2021-12-18 23:31:24
//....................#include"utili.h"
#include<stdio.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<stdlib.h>

//.....................sem_create mysem.c
#include"utili.h"
int main(int argc,char *argv[])
{
key_t sem_key = ftok(argv[1],0xff);
if(sem_key == -1)
{
perror("ftok");
exit(1);
}
/*semget(key_t key,int nsems,int oflag)
关键字 信号量个数 设置信号量的访问权限标志
关于oflag参数:1.IPC_CTEAT 即如果所指定键的IPC对象不存在,就创建一个新对象 否则返回该对象
2.同时设置oflag的IPC——CREAT和IPC——EXCL位时,即如果所指定键的IPC对象不存在,就创建一个新的对象,否则返回一个EEXIST错误,因为该对象已存在
*/
int sem_id = semget(sem_key,1,IPC_CREAT|IPC_EXCL|0755);
if(sem_id == -1)
{
perror("semget");
exit(1);
}
printf("create sem ok.\n");
return 0;
}

//...................................sem_get.c
#include"utili.h"
int main(int argc,char *argv[])
{
key_t sem_key = ftok(argv[1],0xff);
int sem_id = semget(sem_key,0,0);//创建信号量

int val = semctl(sem_id,0,GETVAL); //semctl控制函数
printf("sem_val = %d\n",val); //val= 0 没有资源 阻塞
return 0;
}

// ........................................ set_sem.c
#include"utili.h"
union semun
{
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL*/
struct seminfo *__buf; /* Buffer for IPC_INFO
(Linux-specific) */

};
//设置信号量
int main(int argc,char *argv[])
{
key_t sem_key = ftok(argv[1],0xff);
int sem_id = semget(sem_key,0,0);

union semun val;
val.val =atoi(argv[2]); //atoi 将字符串转换为整型数
semctl(sem_id,0,SETVAL,val);
return 0;
}

//.............................sem_p.c
#include"utili.h"
int main(int argc,char *argv[])
{
key_t sem_key = ftok(argv[1],0xff);
int sem_id = semget(sem_key,0,0);

struct sembuf op;
op.sem_num = 0;
op.sem_op = -1;
// op.sem_flg = 0;
op.sem_flg = SEM_UNDO;
semop(sem_id,&op,1);
return 0;
}
sem_v.c
#include"utili.h"
/*
信号量的值仅能由pv操作来改变
PV操作通过调用函数semop来实现
int semop(int semid,struct sembuf *sops ,size_t nsops);
标示符 sops指向结构体数组的首地址 信号的个数

struct sembuf
{
ushort sem_num; //信号在信号集中的索引
short sem_op; //操作类型
short sem_flg; //操作标志
}
*/

int main(int argc,char *argv[])
{
key_t sem_key = ftok(argv[1],0xff);
int sem_id = semget(sem_key,0,0);

struct sembuf op;
op.sem_num = 0;
op.sem_op =1;
op.sem_flg = 0;

semop(sem_id,&op,1);
return 0;
}

//........................sem_remove.c
#include"utili.h"
int main(int argc,char *argv[])
{

key_t sem_key = ftok(argv[1],0xff);
int sem_id = semget(sem_key,0,0);

int res = semctl(sem_id,0,IPC_RMID);
if(res == -1)
{
printf("remove sem Erroe.\n");
}
else
printf("remove sem Ok.\n");
return 0;
}