Linux 高并发学习笔记 - 共享内存

共享内存是Linux系统中实现进程间通信的一种高效方式,它在物理内存中开辟空间,避免了磁盘操作,提高效率。主要涉及shmget创建/获取共享内存,shmat连接共享内存,shmdt断开连接以及shmctl管理(如删除)共享内存等函数。
摘要由CSDN通过智能技术生成
2.3.7 共享内存

Linux 高并发学习笔记 - 笔记索引

共享内存原理
  • 共享内存Shared Memory)与内存映射技术相仿。但不同的是,内存映射建立了与磁盘空间的同步关系(不考虑匿名内存映射),这意味着内存映射同样需要操作磁盘;而共享内存物理内存中开辟空间,为不同进程建立相同的虚拟内存映射,无需操作磁盘,效率更高。
  • 共享内存必须是页(即4096Bytes)的倍数,不足4096Bytes的倍数向上取整倍。
  • 共享内存位于虚拟内存空间共享区
共享内存操作
  • shmget
#include <sys/ipc.h>
#include <sys/shm.h>
// 	get or create a shared memory
// 		key:
// 			the shared memory key to get or create (depending on "shmflg")
// 		size:
// 			the size of shared memory to create
// 			if getting a shared memory, size can be any but no more than exactly size of shared memory
// 		shmflg:
// 			(default):
// 				get a shared memory, otherwise raise an error
// 			IPC_CREAT:
// 				if the shared memory id not found, a new memory will be create
// 			IPC_EXCL:
// 				if the shared memory id already exists, an error will be raise
// 				it should be used with IPC_CREAT
// 			* others:
// 				if IPC_CREAT is chosen, you should OR-ed with the permission mode on "shmflg"
// 		return value:
// 			the shmid (different to key), or -1 for error
int shmget(key_t key, size_t size, int shmflg);

// About more
// $ man 2 shmget
  • shmatshmdt
// 	attach the shared memory to the process
// 		shmid:
// 			shmid getting from "shmget"
// 		shmaddr:
// 			Address base of the memory, it's a hint of address to kernel but not exactly the address.
// 			Usually NULL is given.
// 		shmflg:
// 			(default):
// 				read and write permisson
// 			SHM_EXEC:
// 				execute permission
// 			SHM_RDONLY:
// 				readonly (remove the write permisson)
// 		return value:
// 			exact memory address, or -1 for error
void *shmat(int shmid, const void *shmaddr, int shmflg);

// 	detach the shared memory from the process
// 		shmaddr:
// 			address of shared memory getting from "shmat"
// 		return value:
// 			return 0 for success, or -1 for error
int shmdt(const void *shmaddr);

// About more
// $ man 2 shmat
  • shmctl
// 	free the shared memory (and other functioms, see in more)
// 		shmid:
// 			shmid getting from "shmget"
// 		cmd:
// 			IPC_RMID:
// 				remove the shared memory
// 		buf:
// 			NULL
int shmctl(int shmid, int cmd, struct shmid_ds *buf);

// About more
// $ man 2 shmctl
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值