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   

查看共享内存。

相关推荐
-VE-10 分钟前
myshell
linux·c++
身在江湖的郭大侠2 小时前
Linux内核
linux·服务器
破-风4 小时前
linux的用法
linux·运维·服务器
涛ing8 小时前
32. C 语言 安全函数( _s 尾缀)
linux·c语言·c++·vscode·算法·安全·vim
__雨夜星辰__8 小时前
Linux 学习笔记__Day2
linux·服务器·笔记·学习·centos 7
大耳朵土土垚8 小时前
【Linux】日志设计模式与实现
linux·运维·设计模式
深度Linux13 小时前
Linux网络编程中的零拷贝:提升性能的秘密武器
linux·linux内核·零拷贝技术
chian-ocean16 小时前
从理论到实践:Linux 进程替换与 exec 系列函数
linux·运维·服务器
拎得清n17 小时前
UDP编程
linux
敖行客 Allthinker17 小时前
从 UTC 日期时间字符串获取 Unix 时间戳:C 和 C++ 中的挑战与解决方案
linux·运维·服务器·c++