一.IPC之共享内存
1.进程间通信的三种方法:
- 消息队列
- 信号量
- 共享内存
2.共享内存的优点:
运行时省去了若干次拷贝,是以上三种程序间通信中最快的
3.共享内存的缺点
消息队列 管道等自带同步或互斥机制,而共享内存不自带,故需要使用信号量来实现共享内存的互斥和同步。
二.用代码实现共享内存
1.创建共享内存//int Creat_shm(int size)
创建代码调用的函数
以上图片中shmflg的参数若为2
的活则有内存则打开,无则创建,若为1和2
的话无则创建有则报错。
2获取代码//int Get_shm()
3.摧毁共享内存//int Destory_shm(int shmid)
摧毁内存调用的函数
4.其他函数
- 关联函数//
作用是将页表和物理内存的共享内存关联起来
- 去关联函数//
在页表中释放关联函数关联的地址
三.源代码
1.comm.h
#ifndef _COMM_H_
#define _COMM_H_
#include<errno.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#include<sys/types.h>
#define PATHNAME "."
#define PROJ_ID 0x6666
int Creat_shm(int size);
int Get_shm();
int Destory_shm(int shmid);
#endif
2.comm.c
#include"comm.h"
int comm_shm(int size,int flags)
{
int key=ftok(PATHNAME,PROJ_ID);
if(key<0)
{
perror("ftok");
return -1;
}
int shmid=shmget(key,size,flags);
if(shmid<0)
{
perror("shmid");
return -2;
}
return shmid;
}
int Creat_shm(int size)
{
return comm_shm(4096,IPC_CREAT|IPC_EXCL|0666);
}
int Get_shm()
{
return comm_shm(0,IPC_CREAT);
}
int Destory_shm(int shmid)
{
if(shmctl(shmid,IPC_RMID,NULL)<0)
{
perror("shmctl");
return -1;
}
}
3.server.c
#include"comm.h"
int main()
{
int count=0;
int shmid=Creat_shm(4096);
sleep(5);
char* sh_mat=shmat(shmid,NULL,0);
sleep(5);
while(count<4096)
{
sh_mat[count]='A'+count%26;
sleep(1);
count++;
sh_mat[count]=0;
}
shmdt(sh_mat);
sleep(5);
Destory_shm(shmid);
return 0;
}
4.client.c
#include"comm.h"
int main()
{
int shmid = Get_shm();
sleep(5);
char* shm_at=shmat(shmid,NULL,0);
while(1)
{
printf("%s\n",shm_at);
sleep(1);
}
shmdt(shm_at);
return 0;
}
四.运行结果图