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

0. 共享内存

  • 比喻
    火锅

  • 本质

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

在这里插入图片描述

1. POSIX 共享内存

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

2. 分类

  1. 内存映射文件
    在这里插入图片描述

内存映射文件

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

  1. 共享内存区对象(非亲缘进程)
    在这里插入图片描述

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

风格方式
BSDMAP_ANON+mmap()
Systerm V/dev/zero+open()

3 接口

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

3.1 函数

POSIX 共享内存有6个函数,其中5,6为文件操作函数,使用内存映射文件。

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)
5获取文件信息int fstat(int fd,struct stat *buf))
6关闭内存映射int ftruncate(int fd,struct stat *buf,off_t length))

*案例:查看文件大小并进行修改,可以变成0;
./filename file_name new_size

  1. 头文件
#include <fcntl.h> // open() O_RDONLY
#include <sys/stat.h> // stat()
#include <unistd.h> // ftruncate()
  1. atoi()将字符串转化为数字
truncate(argv[1],atoi(argv[2]));  //(2)atoi()将字符串转化为数字
  1. 表示文件执行的时候的参数说明(终端输入)
int main(int argc,char* argv[]){  //(1)表示文件执行的时候的参数类型(终端输入)

补充说明代码(main.cpp)

#include <iostream>
using namespace std;

int main(int argc,const char* const argv[]){
    for(int i=0;i<argc;++i){
        cout << i << ":" << argv[i] << endl;
    }
}
  • 完整案例
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h> // open() O_RDONLY
#include <sys/stat.h> // stat()
#include <unistd.h> // ftruncate()
using namespace std;
// ./filesize file_name new_size
int main(int argc,char* argv[]){  //(1)表示文件执行的时候的参数类型(终端输入)
    if(3!=argc){
        cout << "Using:" << argv[0] << " file_name new_size"  << endl;
        return EXIT_FAILURE;
    }
/*
    int fd = open(argv[1],O_RDWR);
    if(-1 == fd){
        perror("open file error");
        return EXIT_FAILURE;
    }

    struct stat s;
    fstat(fd,&s);
    cout << argv[1] << ":"<< s.st_size << endl;

    ftruncate(fd,atoi(argv[2]));

    fstat(fd,&s);
    cout << argv[1] << ":"<< s.st_size << endl;
*/
    struct stat s;
    stat(argv[1],&s);
    cout << argv[1] << ":"<< s.st_size << endl;

    truncate(argv[1],atoi(argv[2]));  //(2)atoi()将字符串转化为数字

    stat(argv[1],&s);
    cout << argv[1] << ":"<< s.st_size << endl;
    return EXIT_SUCCESS;
}

3.1.1 创建

  int shm_open(const char *name, int oflag, mode_t mode)
  • 参数
No.参数含义
1nameposix IPC名字,格式为/somename
2oflag标志
3mode权限
  • 标志
No.标志作用
1O_CREAT没有该对象则创建
2O_EXCL如果O_CREAT指定,但name不存在,就返回错误
3O_NONBLOCK以非阻塞方式打开消息队列
4O_RDONLY只读
5O_RDWR读写
6O_WRONLY只写
7O_TRUNC若存在则截断
  • 权限
No.权限作用
1S_IWUSR用户/属主写
2S_IRUSR用户/属主读
3S_IWGRP组成员写
4S_IRGRP组成员读
5S_IWOTH其他用户写
6S_IROTH其他用户读
  • 返回值
No.返回值含义
1-1出错
2其他共享内存描述符
  • 创建内存共享
    1.编写源代码
    1.1参数(1,文件名,2,操作方式3,权限)
int fd = shm_open(argv[1],O_CREAT|O_RDWR,0644); //参数(1,文件名,2,操作方式3,权限)
  • 完整案例
   #include <iostream>
#include <cstdlib>
#include <cstdio>
#include <fcntl.h> // O_CREAT
#include <sys/mman.h> // shm_open()
#include <unistd.h> // ftruncate()

using namespace std;

// ./shm_open file_name file_size
int main(int argc,char* argv[]){

   if(3 != argc){
        cout << "Using:" << argv[0] << " file_name file_size" << endl;
        return EXIT_FAILURE;
   }

   // 创建共享内存文件 
   int fd = shm_open(argv[1],O_CREAT|O_RDWR,0644); //参数(1,文件名,2,操作方式3,权限)
   if(-1 == fd){
        perror("create error");
        return EXIT_FAILURE;
   }

   // 1.2 一定要修改大小
   ftruncate(fd,atoi(argv[2]));

   return EXIT_SUCCESS;
}

1.2编译:,注意连接库

g++ 002_shm_open.cpp -o 002_shm_open -lrt

1.3执行:,二进制文件名 /文件名 size
注意:文件存在/dev/shm里面

./002_shm_open /abc 200
ll /dev/shm

3.1.2 删除

int shm_unlink(const char *name)
  • 参数
No.参数含义
1nameposix IPC名字
  • 返回值
No.返回值含义
1-1出错
20成功
  • 示例

1.编写源码

 #include <iostream>
#include <cstdlib>
#include <cstdio>
#include <fcntl.h> // O_CREAT
#include <sys/mman.h> // shm_open()
#include <unistd.h> // ftruncate()

using namespace std;

// ./shm_unlink file_name
int main(int argc,char* argv[]){

   if(2 != argc){
        cout << "Using:" << argv[0] << " file_name" << endl;
        return EXIT_FAILURE;
   }

   // 删除
   int res = shm_unlink(argv[1]);
   if(-1 == res){
        perror("delete error");
        return EXIT_FAILURE;
   }
   return EXIT_SUCCESS;
}

1.2编译:,注意连接库

g++ 002_shm_unlink.cpp -o 002_shm_unlink -lrt

1.3执行:,二进制文件名 /文件名
注意:文件存在/dev/shm里面

./002_shm_unlink /abc 
ll /dev/shm

3.1.3 建立内存映射

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

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

  • 内存保护标志
No.参数含义
1PROT_EXEC页内容可以被执行
2PROT_READ页内容可以被读取
3PROT_WRITE页可以被写入
4PROT_NONE页不可访问,不能与文件的打开模式冲突
  • 映射对象的类型
No.参数含义
1MAP_SHARED变动共享
2MAP_PRIVATE变动私有
3MAP_ANON匿名内存映射
  • 返回值
No.返回值含义
1MAP_FAILED失败
2非MAP_FAILED共享内存地址

3.1.4 关闭内存映射

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

3.2 内存映射文件

3.2.1 写文件

1.1编写源码
(1.1.1) 创建文件;(注意shm_open()里面的参数)

  int fd = shm_open(argv[1],O_RDWR,0);
   if(-1 == fd){
        perror("open error");
        return EXIT_FAILURE;
   }

(1.1.2) 建立映射
参数一;默认为空;随机访问(系统)
参数二:大小
参数三;操作;
参数四:权限(共享)
参数五:描述符
参数六:返回的指针大小,默认

 void* buf = mmap(NULL,100,PROT_WRITE,MAP_SHARED,fd,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }

1.1.3内存操作,默认为memcpy,这里特化为strcpy

 string str;
   getline(cin,str);
   strcpy(reinterpret_cast<char*>(buf),str.c_str())

1.1.4 解除映射
munmap(buf,100);

  • 完整案例
   #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h> // O_CREAT
#include <sys/mman.h> // shm_open()
#include <unistd.h> // ftruncate()
#include <cstring> //strcpy()

using namespace std;

// ./shm_write file_name
int main(int argc,char* argv[]){

   if(2 != argc){
        cout << "Using:" << argv[0] << " file_name" << endl;
        return EXIT_FAILURE;
   }

   // (1) 创建文件;(注意shm_open()里面的参数)
   int fd = shm_open(argv[1],O_RDWR,0);
   if(-1 == fd){
        perror("open error");
        return EXIT_FAILURE;
   }

   // (2)建立映射
   //参数一;默认为空;随机访问(系统)
//参数二:大小
//参数三;操作;
//参数四:权限(共享)
//参数五:描述符
//参数六:返回的指针大小,默认
   void* buf = mmap(NULL,100,PROT_WRITE,MAP_SHARED,fd,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }
   
   // 1.3内存操作,默认为memcpy,这里特化为strcpy
   string str;
   getline(cin,str);
   strcpy(reinterpret_cast<char*>(buf),str.c_str());

   //1.4 解除映射
   munmap(buf,100);

   return EXIT_SUCCESS;
}

1.2 编译

g++ 004_shm_write.cpp -o 004_shm_write -lrt

1.3 执行

./004_shm_write /abc
abcdefg
  • 问题
    如果没有ftruncate(fd,sizeof(str));会出现什么情况?(不能修改大小)

3.2.2. 读文件

2.1源码
2.1.1读操作,注意参数

 // 建立映射
   void* buf = mmap(NULL,100,PROT_READ,MAP_SHARED,fd,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }
  • 完整案例
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h> // O_CREAT
#include <sys/mman.h> // shm_open()
#include <unistd.h> // ftruncate()
#include <cstring> //strcpy()

using namespace std;

// ./shm_read file_name
int main(int argc,char* argv[]){

   if(2 != argc){
        cout << "Using:" << argv[0] << " file_name" << endl;
        return EXIT_FAILURE;
   }

   // 打开共享内存文件
   int fd = shm_open(argv[1],O_RDWR,0);
   if(-1 == fd){
        perror("open error");
        return EXIT_FAILURE;
   }

   // 建立映射
   void* buf = mmap(NULL,100,PROT_READ,MAP_SHARED,fd,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }
   
   cout << reinterpret_cast<char*>(buf) << endl;

   // 解除映射
   munmap(buf,100);

   return EXIT_SUCCESS;
}

2.2 编译

g++ 005_shm_read.cpp -o 005_shm_read -lrt

2.3 执行

./005_shm_write /abc

4.非亲缘

4.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);
    }

5 亲缘进程

5.1 亲缘进程读写数据(实名)

  1. 打开共享内存文件
   int fd = shm_open(argv[1],O_RDWR,0);
   if(-1 == fd){
        perror("open error");
        return EXIT_FAILURE;
   }
  1. 建立映射
  char* buf = (char*)mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }
  1. 父子进程
 if(0==fork()){ //子进程
        strcpy(buf,"Test");
   }else{ // 父进程
        cout << buf << endl;
   }
  • 完整案例
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h> // O_CREAT
#include <sys/mman.h> // shm_open()
#include <unistd.h> // ftruncate()
#include <cstring> //strcpy():

using namespace std;

// ./shm_read file_name
int main(int argc,char* argv[]){

   if(2 != argc){
        cout << "Using:" << argv[0] << " file_name" << endl;
        return EXIT_FAILURE;
   }

   // 打开共享内存文件
   int fd = shm_open(argv[1],O_RDWR,0);
   if(-1 == fd){
        perror("open error");
        return EXIT_FAILURE;
   }

   // 建立映射
   char* buf = (char*)mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }
   
   // 
   if(0==fork()){ //子进程
        strcpy(buf,"Test");
   }else{ // 父进程
        cout << buf << endl;
   }

   // cout << reinterpret_cast<char*>(buf) << endl;

   // 解除映射
   munmap(buf,100);

   return EXIT_SUCCESS;
}

5.2 亲缘进程读写数据(匿名1)

  • Systerm V风格
  1. 打开匿名共享内存
   int fd = open("/dev/zero",O_RDWR);
   if(-1 == fd){
        perror("open error");
        return EXIT_FAILURE;
   }
  1. 建立映射
char* buf = (char*)mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }
  1. 父子进程
  if(0==fork()){ //子进程
        strcpy(buf,"Test");
   }else{ // 父进程
        sleep(1);
        cout << buf << endl;
   }
  • 完整案例
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h> // O_CREAT
#include <sys/mman.h> // shm_open()
#include <unistd.h> // ftruncate()
#include <cstring> //strcpy()

using namespace std;

// ./shm_read file_name
int main(int argc,char* argv[]){

/*   if(2 != argc){
        cout << "Using:" << argv[0] << " file_name" << endl;
        return EXIT_FAILURE;
   }
*/
   // 打开匿名共享内存
   int fd = open("/dev/zero",O_RDWR);
   if(-1 == fd){
        perror("open error");
        return EXIT_FAILURE;
   }

   // 建立映射
   char* buf = (char*)mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }
   
   // 
   if(0==fork()){ //子进程
        strcpy(buf,"Test");
   }else{ // 父进程
        sleep(1);
        cout << buf << endl;
   }

   // cout << reinterpret_cast<char*>(buf) << endl;

   // 解除映射
   munmap(buf,100);

   return EXIT_SUCCESS;
}

5.3 亲缘进程读写数据(匿名2)

. * BSD风格

  1. 建立映射(不用建立共享文件 )
 char* buf = (char*)mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANON,-1,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }
  1. 父子进程
   if(0==fork()){ //子进程
        strcpy(buf,"Test");
   }else{ // 父进程
        sleep(1);
        cout << buf << endl;
   }
  • 完整案例
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h> // O_CREAT
#include <sys/mman.h> // shm_open()
#include <unistd.h> // ftruncate()
#include <cstring> //strcpy()

using namespace std;

// ./shm_read file_name
int main(int argc,char* argv[]){

/*   if(2 != argc){
        cout << "Using:" << argv[0] << " file_name" << endl;
        return EXIT_FAILURE;
   }
*/
   // 打开匿名共享内存
/*
   int fd = open("/dev/zero",O_RDWR);
   if(-1 == fd){
        perror("open error");
        return EXIT_FAILURE;
   }
*/
   // 1. 建立映射(不用建立共享文件 )
   char* buf = (char*)mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANON,-1,0);
   if(MAP_FAILED == buf){
        perror("mmap error");
        return EXIT_FAILURE;
   }
   
   // 2.父子进程
   if(0==fork()){ //子进程
        strcpy(buf,"Test");
   }else{ // 父进程
        sleep(1);
        cout << buf << endl;
   }

   // cout << reinterpret_cast<char*>(buf) << endl;

   // 解除映射
   munmap(buf,100);

   return EXIT_SUCCESS;
}

5.4 结果

比较
在这里插入图片描述

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

info proc mapping

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

  1. 现象:总线错误Bus Error
    原因:映射文件的大小为0
    解决:使用ftruncate()扩展文件的大小,stat.st_size。
  2. 现象:段错误
    原因:munmap()解除映射的大小大于申请内存大小
    解决:解除映射大小与申请内存大小保持一直
  3. 现象:Permisstion denied
    原因:文件打开权限与文件映射对象访问权限不一致。
    解决:只读PROT_READ的文件映射对象使用O_RDONLY打开文件;读写PROT_READ|PROT_WRITE的文件映射对象使用O_RDWR打开文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值