一、信号灯的创建与删除
创建函数:
控制函数:
二、结合共享内存实现PV操作
例程如下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#define SEM_READ 0
#define SEM_WRITE 0
union semun
{
int val;
};
void Poperation(int index,int semid)//p操作
{
struct sembuf sop;
sop.sem_num = index;
sop.sem_op = -1;//P
sop.sem_flg = 0;
semop(semid,&sop,1);
}
void Voperation(int index,int semid)//v操作
{
struct sembuf sop;
sop.sem_num = index;
sop.sem_op = 1;//v
sop.sem_flg = 0;
semop(semid,&sop,1);
}
int main()
{
key_t key;
key = ftok(".",123);
pid_t pid;
int semid;
int shmid;
char *shmaddr;
semid = semget(key,2,IPC_CREAT|0755);//创建信号
if(semid < 0)
{
perror("semget");
return -1;
}
shmid = shmget(key,128,IPC_CREAT|0755);//创建共享内存
if(shmid < 0)
{
perror("shmget");
return -2;
}
//init semaphore
union semun myun;
//init semaphore read
myun.val = 0;
semctl(semid,SEM_READ,SETVAL,myun);
//init semaphore write
myun.val = 1;
semctl(semid,SEM_WRITE,SETVAL,myun);
pid = fork();//创建父子进程
if(pid == 0)//child process
{
while(1)
{
shmaddr = (char *)shmat(shmid,NULL,0);
Poperation(SEM_READ,semid);//读完才能写
printf("get share memory is:%s\n",shmaddr);
Voperation(SEM_WRITE,semid);
}
}
else if(pid > 0)//parent process
{
while(1)
{
shmaddr = (char *)shmat(shmid,NULL,0);
Poperation(SEM_WRITE,semid);//写完才能读
printf("please input message to memory:\n");
fgets(shmaddr,32,stdin);
Voperation(SEM_READ,semid);
}
}
return 0;
}
结果如下: