s1 s2
1 0
p(s1) p(s2)
write read
v(s2) v(s1)
刚开始s1可以写入,s2不能读取
写完之后执行p(s1)操作和p(s2)操作,开始读取
读完之后再执行v(s2)操作结束读取
执行v(s1)操作继续写入
//创建文件“sem.h”
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<unistd.h>
#include<sys/sem.h>
#define SEM1 1
#define SEM2 0
union semun
{
int val;
};
void sem_init();
void sem_p(int index);
void sem_v(int index);
void sem_destroy();
//创建文件“sem.c”
#include"sem.h"
#define SEM_NUM 2
static int semid = -1;
void sem_init()
{ semid=semget((key_t)1234,SEM_NUM,IPC_CREAT|IPC_EXCL|0600);
if(semid == -1)
{
semid = semget((key_t)1234,SEM_NUM,0600);
if(semid == -1)
{
perror("semget error");
}
}
else
{
int arr[SEM_NUM] = {1,0};
union semun a;
int i=0;
for(;i<SEM_NUM;i++)
{
a.val = arr[i];
if(semctl(semid,i,SETVAL,a) == -1)
{
perror("semctl setval error");
}
}
}
}
void sem_p(int index)
{
struct sembuf buf;
buf.sem_num = index;
buf.sem_op = -1;
buf.sem_flg = SEM_UNDO;
if(semop(semid,&buf,1)==-1)
{
perror("semop p error");
}
}
void sem_v(int index)
{
struct sembuf buf;
buf.sem_num = index;
buf.sem_op = 1;
buf.sem_flg = SEM_UNDO;
if(semop(semid,&buf,1) == -1)
{
perror("semop p error");
}
}
void sem_destroy()
{
if(semctl(semid,0,IPC_RMID) == -1)
{
perror("semctl ipc_rmid error");
}
}
//创建输出文件 test.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/shm.h>
#include<string.h>
#include<assert.h>
int main()
{
int shmid = shmget((key_t)1234,256,IPC_creat|0600);//创建共享内存或获取一个已存在的共享内存的id
assert( shmid != -1);
char * s = (char*)shmat(shmid,NULL,0);//映射到当期进程地址空间
assert( s !=(char*)-1);
sem_init();
while(1)
{
sem_p(SEM2);
if(strncmp(s,"end",3)==0)
{
break;
}
printf("s=%s\n,s");
sem_v(SEM1);
}
shmdt(s);//断开映射
sem_destroy();
shmctl(shimid,IPC_RMID,NULL);
exit(0);
}
//创建输入文件 main.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<unistd.h>
#include<sys/shm.h>
int main()
{
int shmid = shmget((key_t)1234,256,IPC_creat|0600);
assert( shmid != -1);
char * s = (char*)shmat(shmid,NULL,0);
assert( s !=(char*)-1);
sem_init();
while(1)
{
char buff[128]={0};
printf("input:\n");
fgets(buff,128,stdin);
sem_p(SEM1);
strcpy(s,buff);
sem_v(SEM2);
if(strncmp(buff,"end",3)==0)
{
break;
}
}
shmdt(s);
}