---
title: "Linux C共享内存"
author: "Jameslyy"
date: "2014-09-04T18:11:35Z"
tags: []
categories: ["编程语言"]
slug: "linux-c"
draft: false
lastmod: "2014-09-04T18:13:08Z"
id: 2113441
url: "https://jamesblog.iteye.com/blog/2113441"
---

共享内存相关函数：

 

1. shmid = shmget(IPC\_PRIVATE, SIZE, IPC\_CREAT|0666 ) ;

创建共享内存，如果共享内存已经存在，则获取已经存在的共享内存。

一般不是使用IPC\_PRIVATE作为参数，可以使用 key\_t mid = ftok("./ftok.tmp", 20); 获取共享内存的key。

 

2\.  void \*shmat(int shmid, const void \*shmaddr, int shmflg)

把共享内存区对象映射到调用进程的地址空间

 

3. int shmdt(const void \*shmaddr)

断开共享内存连接

 

4. int shmctl(int shmid, int cmd, struct shmid\_ds \*buf)

共享内存控制。 

CMD参数：

    IPC\_STAT：得到共享内存的状态，把共享内存的shmid\_ds结构复制到buf中

    IPC\_SET：改变共享内存的状态，把buf所指的shmid\_ds结构中的uid、gid、mode复制到shmid\_ds结构内

    IPC\_RMID：删除共享内存

查看共享内存命令：ipcs -m