Linux系统编程5:IPC共享内存

0. 共享内存

  • 比喻


    火锅
  • 本质

    • 多个进程访问同一个逻辑内存
    • 直接访问内存,不用read()/write()非常方便

1. POSIX 共享内存

  • 资料:unpv22e-ch13
  • 查看:
    • man shm_overview
    • ls /dev/shm

2. 分类

  1. 内存映射文件

    内存映射文件

    注意:共享内存大小 = 文件大小

  2. 共享内存区对象(非亲缘进程)

  1. 匿名内存映射(亲缘进程)
风格 方式
BSD MAP_ANON+mmap()
Systerm V /dev/zero+open()

3 接口

  • 头文件:sys/mman.h
  • 库:librt.so

3.1 函数

POSIX 共享内存有几个函数。

No. 操作 函数
1 创建 int shm_open(const char *name, int oflag, mode_t mode)
2 删除 int shm_unlink(const char *name)
3 建立内存映射 void* mmap(void* start,size_t length,int prot,int flags,int fd,off_t offset)
4 关闭内存映射 int munmap(void *start,size_t length)

3.1.1 创建

int shm_open(const char *name, int oflag, mode_t mode)
  • 参数
No. 参数 含义
1 name posix IPC名字,格式为/somename
2 oflag 标志
3 mode 权限
  • 标志
No. 标志 作用
1 O_CREAT 没有该对象则创建
2 O_EXCL 如果O_CREAT指定,但name不存在,就返回错误
3 O_NONBLOCK 以非阻塞方式打开消息队列
4 O_RDONLY 只读
5 O_RDWR 读写
6 O_WRONLY 只写
7 O_TRUNC 若存在则截断
  • 权限
No. 权限 作用
1 S_IWUSR 用户/属主写
2 S_IRUSR 用户/属主读
3 S_IWGRP 组成员写
4 S_IRGRP 组成员读
5 S_IWOTH 其他用户写
6 S_IROTH 其他用户读
  • 返回值
No. 返回值 含义
1 -1 出错
2 其他 共享内存描述符
  • 示例
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = shm_open(argv[1],O_CREAT|O_RDWR,0644);
    ftruncate(fd,atoi(argv[2]));
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_WRITE,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
}

3.1.2 删除

int shm_unlink(const char *name)
  • 参数
No. 参数 含义
1 name posix IPC名字
  • 返回值
No. 返回值 含义
1 -1 出错
2 0 成功
  • 示例
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    shm_unlink(argv[1]);
}

3.1.3 建立内存映射

void* mmap(void* start,size_t length,int prot,int flags,int fd,off_t offset)
  • 参数
No. 参数 含义
1 start 映射区的开始地址,通常使用NULL,让系统决定映射区的起始地址
2 length 映射区的长度,单位字节,不足一内存页按一内存页处理
3 prot 内存保护标志
4 flags 映射对象的类型
5 fd 文件描述符,不能是套接字和终端的fd-1为匿名内存映射
6 offset 被映射对象内容的起点,只能是页大小的整数倍

如何获取页大小? sysconf(_SC_PAGESIZE)

  • 内存保护标志
No. 参数 含义
1 PROT_EXEC 页内容可以被执行
2 PROT_READ 页内容可以被读取
3 PROT_WRITE 页可以被写入
4 PROT_NONE 页不可访问,不能与文件的打开模式冲突
  • 映射对象的类型
No. 参数 含义
1 MAP_SHARED 变动共享
2 MAP_PRIVATE 变动私有
3 MAP_ANON 匿名内存映射
  • 返回值
No. 返回值 含义
1 MAP_FAILED 失败
2 MAP_FAILED 共享内存地址
  • 示例
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = shm_open(argv[1],O_RDWR,0);
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_WRITE,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    strcpy(buf,argv[2]);
    munmap(buf,BUFSIZ);
}

#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = shm_open(argv[1],O_RDONLY,0);
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_READ,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    printf("%s\n",buf);
    munmap(buf,BUFSIZ);
}

3.1.4 关闭内存映射

int munmap(void *start,size_t length)
  • 参数
No. 参数 含义
1 start 映射内存起始地址
2 length 内存大小
  • 返回值
No. 返回值 含义
1 0 成功
2 -1 失败
  • 注意
    关闭mmap中的文件描述符不能删除内存映射。

4 示例

4.1 内存映射文件

  1. 创建文件并且写入数据
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(){
    int fd = open("./mmap.txt",O_CREAT|O_RDWR,0644);
    char str[] = "hello mmap\n";    
    ftruncate(fd,sizeof(str));
    void* buf = NULL;
    if(( buf =  mmap(NULL,sizeof(str),PROT_WRITE,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    strcpy(buf,str);
    munmap(buf,sizeof(str));
    close(fd);
}

问题
如果没有ftruncate(fd,sizeof(str));会出现什么情况?

  1. 读取数据并且重新写入数据
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = open("./mmap.txt",O_RDWR);
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    printf("%s\n",buf);
    strcpy(buf,"this sdfdsfdsfdsfdsfdsfdsfdsfdsfdsf\n");
    munmap(buf,BUFSIZ);
    close(fd);
}
  1. 亲缘进程读写数据
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = open("./mmap.txt",O_CREAT|O_RDWR,0644);
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_WRITE|PROT_READ,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    if(fork()){
        strcpy(buf,argv[1]);    
    }else{
        printf("%s\n",buf);
    }
    munmap(buf,BUFSIZ);
    close(fd);
}
  1. 非亲缘进程读写数据
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = open("./mmap.txt",O_CREAT|O_RDWR,0644);
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_WRITE|PROT_READ,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    strcpy(buf,argv[1]);    
    munmap(buf,BUFSIZ);
    close(fd);
}

#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = open("./mmap.txt",O_CREAT|O_RDWR,0644);
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_WRITE|PROT_READ,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    printf("%s\n",buf);
    munmap(buf,BUFSIZ);
    close(fd);
}

4.2 共享内存区对象(非亲缘进程)

#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = shm_open(argv[1],O_RDWR,0);
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_WRITE,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    int i;
    for(i=2;i<argc;i++){
        strcpy(buf,argv[i]);    
        sleep(3);
    }
    munmap(buf,BUFSIZ);
    close(fd);
}

#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = shm_open(argv[1],O_RDONLY,0);
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_READ,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    sleep(1);
    for(;;){
        printf("read:%s\n",buf);
        sleep(3);
    }
    munmap(buf,BUFSIZ);
    close(fd);
}

4.3 匿名内存映射(亲缘进程)

  1. Systerm V风格
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    int fd = open("/dev/zero",O_RDWR);
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_WRITE|PROT_READ,MAP_SHARED,fd,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    if(fork()){
        strcpy(buf,argv[1]);    
    }else{
        printf("%s\n",buf);
    }
    munmap(buf,BUFSIZ);
    close(fd);
}
  1. BSD风格
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
 
int main(int argc,char* argv[]){
    void* buf = NULL;
    if(( buf =  mmap(NULL,BUFSIZ,PROT_WRITE|PROT_READ,MAP_SHARED|MAP_ANON,-1,0)) == MAP_FAILED){
        perror("mmap error\n");
        return 1;
    }
    if(fork()){
        strcpy(buf,argv[1]);    
    }else{
        printf("%s\n",buf);
    }
    munmap(buf,BUFSIZ);
}

比较


实验
使用gdb查看共享内存的建立映射和解除映射。

info proc mapping

5. 使用mmap容易出现的问题

  1. 现象:总线错误Bus Error
    原因:映射文件的大小为0
    解决:使用ftruncate()扩展文件的大小,stat.st_size
  2. 现象:段错误
    原因:munmap()解除映射的大小大于申请内存大小
    解决:解除映射大小与申请内存大小保持一直
  3. 现象:Permisstion denied
    原因:文件打开权限与文件映射对象访问权限不一致。
    解决:只读PROT_READ的文件映射对象使用O_RDONLY打开文件;读写PROT_READ|PROT_WRITE的文件映射对象使用O_RDWR打开文件
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,869评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,716评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,223评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,047评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,089评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,839评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,516评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,410评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,920评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,052评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,179评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,868评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,522评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,070评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,186评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,487评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,162评论 2 356

推荐阅读更多精彩内容