Linux中的共享内存

复制代码
#include <sys/ipc.h>
       #include <sys/shm.h>

       int shmget(key_t key, size_t size, int shmflg);

shmflg:

IPC_CREAT:

如果不存在,创建之,如果存在获取之。

IPC_EXCL:

1.无法单独使用

2.IPC_CREAT|IPC_EXCL:如果不存在,创建之,如果出错就返回给用户。

如果创建成功,一定是一个新的shm!

key_t key:

能够标定唯一性。看到同一个key就具备了看到同一份资源的可能性。

通过ftok创建key

复制代码
 #include <sys/types.h>
       #include <sys/ipc.h>

       key_t ftok(const char *pathname, int proj_id);

操作系统给用户提供的资源上线 ulimit -a

操作系统禁止捕捉9号信号。

共享内存=物理内存块+共享内存的相关属性。

复制代码
 ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status  

查看共享内存。

共享内存的生命周期是随OS的,不是随进程的!!!

删除共享内存使用shmid!!!

复制代码
#include <sys/types.h>
       #include <sys/shm.h>

       void *shmat(int shmid, const void *shmaddr, int shmflg);

       int shmdt(const void *shmaddr);

通过shmat使共享内存和进程实现关联。

**shmaddr:**指定虚拟地址让共享内存映射到指定的虚拟地址。通常设为null

shmflg:与读写权限有关,通常设为0;

shmat:返回的是共享空间的起始地址。

复制代码
ipcrm -m 65536

删除共享内存。

复制代码
ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status   

查看共享内存。

相关推荐
Zhang~Ling9 小时前
从 fopen 到 struct file:从零开始拆解 Linux 文件 I/O
linux·运维·服务器
DeeplyMind9 小时前
Linux 深入 per-VMA lock:Linux 缺页路径如何摆脱 mmap_lock
linux·per-vma lock
爱写代码的森9 小时前
蒙三方库 | harmony-utils之FileUtil文件重命名与属性查询详解
linux·运维·服务器·华为·harmonyos·鸿蒙·huawei
XMAIPC_Robot10 小时前
软硬协同实时控制|RK3588业务调度+FPGA硬件时序,ethercat实现半导体设备微秒级响应(125us)
linux·arm开发·人工智能·fpga开发
重生的黑客11 小时前
Linux 进程优先级、切换与调度:从孤儿进程到 O(1) 调度模型
linux·运维·服务器·进程优先级·nice
骑上单车去旅行12 小时前
MD5校验对比脚本
linux·服务器·windows
平生幻12 小时前
Linux 常用命令
linux
ShirleyWang01213 小时前
让headlamp控制台能访问
linux·服务器·python·k8s·k3s
liuccn13 小时前
Linux 存储系统:LVM 与直接分区
linux·运维
IT曙光15 小时前
在Ubuntu上本地部署Dify?
linux·ubuntu