一、信号灯的创建与删除
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdlib.h>
//信号灯的创建与删除
int main()
{
int semid;
semid = semget(IPC_PRIVATE,3,0777);
if(semid < 0)
{
printf("create semaphore failed\n");
return -1;
}
printf("create semaphore success,semid is %d\n",semid);
system("ipcs -s");
semctl(semid,0,IPC_RMID,NULL);
system("ipcs -s");
return 0;
}
二、信号灯的PV操作
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
//信号灯PV操作
#define SEM_READ 0
#define SEM_WRITE 0
union semun
{
int val;
};
void Poperation(int index,int semid)
{
struct sembuf sop;
sop.sem_num = index;
sop.sem_op = -1;
sop.sem_flg = 0;
semop(semid,&sop,1);
}
void Voperation(int index,int semid)
{
struct sembuf sop;
sop.sem_num = index;
sop.sem_op = 1;
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)//father process
{
while(1)
{
shmaddr = (char *)shmat(shmid,NULL,0);
Poperation(SEM_WRITE,semid);
printf("please input to share memory:\n");
fgets(shmaddr,32,stdin);
Voperation(SEM_READ,semid);
}
}
return 0;
}