共享内存函数接口
<h1 id="共享内存">共享内存</h1><p>共享内存是物理内存中的一段内存空间,而物理内存是由内核进行维护的,所以进程必须向操作系统申请一块物理内存。</p>
<h2 id="shmget函数">shmget函数</h2>
<p>使用此函数可以向内核申请物理内存</p>
<pre><code>int shmget(key_t key,size_t size,int shmflg)
//key:IPC对象使用的键值,ftok()函数生成一个唯一的键值key
//size:新的共享内存段的大小,其值等于四舍五入之后的PAGE_SIZE倍数的大小
//shmflg:可以是IPC_CREAT和IPC_EXCL
//ret:成功返回共享内存的标识符id,失败返回-1
//notice:创建新的内存段的时候会把该内存段进行清零处理,相应的数据结构体也会被初始化
</code></pre>
<h2 id="shmat函数">shmat函数</h2>
<p>该函数可以实现把共享内存映射到进程的内存空间。</p>
<pre><code>void *shmat(int shmid, const void *shmaddr, int shmflg);
//shmid:共享内存的id
//shmaddr:映射后的地址,一半由系统指定,填NULL即可
//shmflg:填0即可,表示默认,权限为可读可写
//ret:成功返回追加成功的共享内存的地址,失败返回(void *) -1
</code></pre>
<h2 id="shmdt函数">shmdt函数</h2>
<p>此函数可以解除映射</p>
<pre><code>int shmdt(const void *shmaddr);
//shmaddr:是shmat函数的返回值
//ret:成功返回0,失败返回-1
</code></pre>
<h2 id="shmctl函数">shmctl函数</h2>
<p>该函数实现设置共享内存的属性、获取共享内存的属性、删除共享内存等相关操作。</p>
<pre><code>struct shmid_ds {
struct ipc_perm shm_perm; /* Ownership and permissions */
size_t shm_segsz; /* Size of segment (bytes) */
time_t shm_atime; /* Last attach time */
time_t shm_dtime; /* Last detach time */
time_t shm_ctime; /* Last change time */
pid_t shm_cpid; /* PID of creator */
pid_t shm_lpid; /* PID of last shmat(2)/shmdt(2) */
shmatt_t shm_nattch;/* No. of current attaches */
...
};
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
//shmid:共享内存的id
//cmd:可以是IPC_SET、IPC_RMID、IPC_INFO等
//buf:结构体的地址
//ret:成功时返回 0,失败时返回 -1,并设置 errno 为相应的错误码。
</code></pre>
<p><img src="https://img2024.cnblogs.com/blog/3626997/202505/3626997-20250508084126035-59075225.png" alt="image" loading="lazy"></p><br><br>
来源:https://www.cnblogs.com/lradian/p/18865569
頁:
[1]