找回密码
 立即注册
首页 业界区 安全 共享内存

共享内存

艾曼语 2025-6-11 15:23:14
共享内存

一、共享内存的概念

共享内存是Linux系统进程间通信的一种方式,是在Unix系统的system-V版本引入的一种IPC对象,除了共享内存外,其他的IPC对象还包含消息队列、信号量组。
共享内存其实就是指多个进程可以共享物理内存中的同一段内存区域,只不过还需要把物理内存映射到进程的私有虚拟地址空间中,这样多个进程就可以对同一块内存进行访问,效率非常高。
1.png

二、申请共享内存

共享内存其实是物理内存中的一段内存空间,而物理内存是由内核进行维护的,所以进程必须向操作系统申请一块物理内存,Linux系统提供了一个名称叫做shmget()的函数接口,利用该接口可以向内核申请物理内存。
shmget()函数的第一个参数指的是key_t类型的键值,和消息队列类似,一般用户可以使用ftok()函数生成一个唯一的键值key。
shmget()函数的第二个参数指的是要申请的共享内存段的大小,由参数size指定,size的大小可以是宏定义PAGE_SIZE的倍数。
shmget()函数的第三个参数指的是共享内存段的标志,其中IPC_CREAT指的是如果共享内存不存在则创建,IPC_EXCL指的是如果共享内存存在则表示函数调用失败。
返回结果:可以看到,函数调用成功,则返回创建成功的共享内存的标识符,函数调用失败,则返回-1。
注意事项:可以看到,申请成功的共享内存段里面存储的内容会被自动初始化为0,并且内核会为每一块创建的共享内存分配一个shmid_ds结构体来记录共享内存的属性和信息。
三、共享内存的映射和控制

用户申请成功共享内存之后是无法直接访问的,因为缺少共享内存的入口地址,另外,由于申请的是物理内存,所以还需要把申请的物理内存映射到进程的内存空间,这样用户就可以通过共享内存入口的虚拟地址来直接访问共享内存空间。
Linux系统提供了一个名称叫做shmat()的函数接口,用户利用该接口可以实现把共享内存映射到进程的内存空。Linux系统来提供了一个名称叫做shmdt()的函数接口,用户利用该接口可以解除映射。
Linux系统内核需要对创建成功的共享内存进行维护,所以会记录每块共享内存的属性和信息,Linux系统提供了一个名称叫做shmctl()的函数接口,用户可以调用该函数实现设置共享内存的属性、获取共享内存的属性、删除共享内存等相关操作。
四、练习

设计三个程序,要求三个程序申请一块共享内存,并分别映射到各自进程的地址空间,进程A和进程B对共享内存段中的数据进行修改,然后进程C不断输出共享内存段中的数据,并观察效果,要求实现进程间的互斥,避免竞争。
进程A
  1. /***************************************************
  2. *
  3. *  file name:        shmA.c
  4. *        author         :  zzlyx1239.126.com
  5. *        date         :  2025/04/3
  6. *        brief    :  进程A,用于对共享内存中的数据进行修改
  7. *         note         :  None
  8. *
  9. *  CopyRight(c) 2025 zzlyx1239.126.com All Reserved
  10. ***************************************************/
  11. #include <unistd.h>
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <fcntl.h>
  15. #include <sys/wait.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <errno.h>
  20. #include <time.h>
  21. #include <sys/ipc.h>
  22. #include <sys/stat.h>
  23. #include <unistd.h>
  24. #include <sys/ipc.h>
  25. #include <sys/shm.h>
  26. #include <sys/sem.h>
  27. char *pshm;
  28. void sign_hander(int)
  29. {
  30.     sprintf(pshm,"I am ProcessA,My PID = %d",getpid());
  31. }
  32. int main()
  33. {
  34.     //1.打开共享内存段,如果不存在则创建,如果存在则打开
  35.         int shm_id = shmget(ftok(".",10),256,IPC_CREAT|IPC_EXCL|0644);
  36.         if (-1 == shm_id)
  37.         {
  38.                 fprintf(stderr, "shmget error,errno:%d,%s\n",errno,strerror(errno));
  39.                 shm_id = shmget(ftok(".",10),256,0644);
  40.         }
  41.     //2.把共享内存段连接到进程空间  shmat()  默认是可读可写  默认会初始化为0
  42.         pshm = (char *)shmat(shm_id,NULL,0);
  43.         if (pshm == (void *)-1)
  44.         {
  45.                 fprintf(stderr, "shmat error,errno:%d,%s\n",errno,strerror(errno));
  46.                 return -1;
  47.         }
  48.     //3.向共享内存中写入数据
  49.     signal(SIGUSR1,sign_hander);
  50.         while(1);
  51.     shmdt(pshm);
  52.     return 0;
  53. }
复制代码
进程B
  1. /***************************************************
  2. *
  3. *  file name:        shmB.c
  4. *        author         :  zzlyx1239.126.com
  5. *        date         :  2025/04/3
  6. *        brief    :  进程B,用于对共享内存中的数据进行修改
  7. *         note         :  None
  8. *
  9. *  CopyRight(c) 2025 zzlyx1239.126.com All Reserved
  10. ***************************************************/
  11. #include <unistd.h>
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <fcntl.h>
  15. #include <sys/wait.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <errno.h>
  20. #include <time.h>
  21. #include <sys/ipc.h>
  22. #include <sys/stat.h>
  23. #include <unistd.h>
  24. #include <sys/ipc.h>
  25. #include <sys/shm.h>
  26. #include <sys/sem.h>
  27. char *pshm;
  28. void sign_hander(int)
  29. {
  30.      sprintf(pshm,"I am ProcessB,My PID = %d",getpid());
  31. }
  32. int main()
  33. {
  34.     //1.打开共享内存段,如果不存在则创建,如果存在则打开
  35.         int shm_id = shmget(ftok(".",10),256,IPC_CREAT|IPC_EXCL|0644);
  36.         if (-1 == shm_id)
  37.         {
  38.                 fprintf(stderr, "shmget error,errno:%d,%s\n",errno,strerror(errno));
  39.                 shm_id = shmget(ftok(".",10),256,0644);
  40.         }
  41.     //2.把共享内存段连接到进程空间  shmat()  默认是可读可写  默认会初始化为0
  42.         pshm = (char *)shmat(shm_id,NULL,0);
  43.         if (pshm == (void *)-1)
  44.         {
  45.                 fprintf(stderr, "shmat error,errno:%d,%s\n",errno,strerror(errno));
  46.                 return -1;
  47.         }
  48.     //3.向共享内存中写入数据  
  49.         signal(SIGUSR2,sign_hander);
  50.         while(1);
  51.     shmdt(pshm);
  52.     return 0;
  53. }
复制代码
进程C
  1. /***************************************************
  2. *
  3. *  file name:        shmC.c
  4. *        author         :  zzlyx1239.126.com
  5. *        date         :  2025/04/3
  6. *        brief    :  进程C,用于对共享内存中的数据进行修改
  7. *         note         :  None
  8. *
  9. *  CopyRight(c) 2025 zzlyx1239.126.com All Reserved
  10. ***************************************************/
  11. #include <unistd.h>
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <fcntl.h>
  15. #include <sys/wait.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <errno.h>
  20. #include <time.h>
  21. #include <sys/ipc.h>
  22. #include <sys/stat.h>
  23. #include <unistd.h>
  24. #include <sys/ipc.h>
  25. #include <sys/shm.h>
  26. #include <sys/sem.h>
  27. int main()
  28. {
  29.     //1.打开共享内存段,如果不存在则创建,如果存在则打开
  30.         int shm_id = shmget(ftok(".",10),256,IPC_CREAT|IPC_EXCL|0644);
  31.         if (-1 == shm_id)
  32.         {
  33.                 fprintf(stderr, "shmget error,errno:%d,%s\n",errno,strerror(errno));
  34.                 shm_id = shmget(ftok(".",10),256,0644);
  35.         }
  36.     //2.把共享内存段连接到进程空间  shmat()  默认是可读可写  默认会初始化为0
  37.         char *pshm = (char *)shmat(shm_id,NULL,0);
  38.         if (pshm == (void *)-1)
  39.         {
  40.                 fprintf(stderr, "shmat error,errno:%d,%s\n",errno,strerror(errno));
  41.                 return -1;
  42.         }
  43.     //3.手动输入进程A和进程B的pid
  44.     int PidA, PidB;
  45.     printf("please input the PID of processA\n");
  46.     scanf("%d", &PidA);
  47.     printf("please input the PID of processB\n");
  48.     scanf("%d", &PidB);
  49.     while(1)
  50.     {
  51.         // 给进程A发送信号
  52.         kill(PidA, SIGUSR1);
  53.         sleep(2);
  54.         // 输出读到的数据
  55.         printf("%s\n", pshm);
  56.         // 给进程B发送信号
  57.         kill(PidB, SIGUSR2);
  58.         sleep(2);
  59.         // 输出读到的数据
  60.         printf("%s\n", pshm);
  61.     }
  62.     shmdt(pshm);
  63.     return 0;
  64. }
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册