linux 共享内存

为什么要使用共享内存??
因为管道与消息队列,在数据的交互时,都要调用我们的系统接口,会减低代码的效率,所以我们就引入共享内存的技术, 来提高数据的交互的速度。

什么时候用管道,什么时候用消息队列,什么时候用共享内存???
假设项目中有两个进程需要频繁的交互数据的话那么就采用共享内存。数据要指定类型的话就用消息队列。

如何创建共享内存:
1.创建key值
#include <sys/types.h>
#include <sys/ipc.h>

   key_t ftok(const char *pathname, int proj_id);
				proj_id ->不能超过255

2.通过key值创建共享内存
NAME
shmget - allocates a System V shared memory segment
创建共享内存
SYNOPSIS
#include <sys/ipc.h>
#include <sys/shm.h>

   int shmget(key_t key, size_t size, int shmflg);
	   参数一:key值 
	   参数二:共享内存的大小    (最好是1024  2048 4096     4字节对其。页)
	   参数三:权限 
				IPC_CREAT -》创建 
				IPC_EXCL  -》检查是否存在  
				mode      -> 0666
				
	   返回值:成功 共享内存对象ID
			   失败 -1

3.把虚拟内存映射到共享内存中
#include <sys/types.h>
#include <sys/shm.h>
//映射
void *shmat(int shmid, const void *shmaddr, int shmflg);
参数一:共享内存对象ID
参数二:填写为NULL 让系统自动选择
参数三:权限
0 -》读写
SHM_RDONLY -》只读

		返回值:  映射后的空间首地址
			     失败: (void *) -1 
   
   
   
		//解除映射
   int shmdt(const void *shmaddr);

4.销毁共享内存
#include <sys/ipc.h>
#include <sys/shm.h>

   int shmctl(int shmid, int cmd, struct shmid_ds *buf);
	   //参数一:操作共享内存对象ID 
	   //参数二:控制命令  IPC_RMID -》删除共享内存 
	   //参数三:获取或设置属性的时候使用
	             删除时 直接填写为 NULL 即可
//send.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h> //错误宏
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>


int main()
{
	//创建一个对象的KEY值 
    key_t key=ftok("/home/gec",88);
	if(key < 0)
	{
		perror("");
		exit(0);
	}

	//创建共享内存 
	 int shmid=shmget(key,1024,IPC_CREAT|0666);
	 if(shmid < 0)
	 {
		 printf("creat fail\n");
		 exit(0);
	 }
	
	//映射共享内存到虚拟内存中 
	 char *p=shmat(shmid,NULL,0);
	if(p == (void *) -1 )
	{
		perror("mmap fail\n");
		exit(0);
	}

	//主进程写入数据
	while(1)
	{
		scanf("%s",p);
		sleep(1);
	}
	 
	 return 0;
}
//recv.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h> //错误宏
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
	//创建一个对象的KEY值 
    key_t key=ftok("/home/gec",88);
	if(key < 0)
	{
		perror("");
		exit(0);
	}

	//创建共享内存 
	int shmid=shmget(key,1024,IPC_CREAT|0666);
	if(shmid < 0)
	{
		printf("creat fail\n");
		exit(0);
	}
	
	//映射共享内存到虚拟内存中 
	char *p=shmat(shmid,NULL,0);
	if(p == (void *) -1 )
	{
		perror("mmap fail\n");
		exit(0);
	}
			
	while(1)
	{
		printf("p=%s\n",p);
		bzero(p,1024);
		sleep(1);
	}
	
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值