ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c-具有非null shmaddr的Shmat

2019-12-10 08:50:57  阅读:386  来源: 互联网

标签:posix shared-memory c-3 linux


有人可以提供一个示例(合理地)将shmat()函数与第二个非空参数一起使用吗?

该手册说:

#include <sys/shm.h>

void *shmat(int shmid, const void *shmaddr, int shmflg);

The shmat() function attaches the shared memory segment associated with the shared memory identifier shmid to the data segment of the calling process. The segment is attached at the address specified by one of the following criteria:

  • If shmaddr is a NULL pointer, the segment is attached at the first available address as selected by the system.
  • If shmaddr is not a NULL pointer and (shmflg & SHM_RND) is non-zero, the segment is attached at the address given by (shmaddr – (shmaddr % SHMLBA)).
  • If shmaddr is not a NULL pointer and (shmflg & SHM_RND) is 0, the segment is attached at the address given by shmaddr.

但是我从未见过将shmaddr设置为NULL的任何shmat实例.在我的项目中,一个进程必须将其附加到malloc()的一块内存上,并且可以很好地使用它,然后另一个进程(通过shmid)获取了指向该共享内存的指针,然后在尝试执行以下操作时出现段错误访问内存.

解决方法:

这里的想法是将共享段放在不同进程中的相同虚拟地址上,以便它们可以使用普通指针(而不是偏移量)来寻址共享内存中的项.常见的情况是单个“主”进程将内存映射到内核提供的地址(第二个参数为零),然后通过一些带外通道将该地址传递给“工作”进程(例如带有fork / exec的命令参数) ,UNIX套接字,FIFO等),然后“工作者”尝试将段映射到该地址.同样,这个想法是,如果内核能够在给定的VA上为“主服务器”映射共享内存,那么对于“工人​​”进程来说,使用相同的地址就可以了.

我没有要指出的“合理”例子.您可以看一下Postgres如何与共享内存一起工作.不过有点涉及.

标签:posix,shared-memory,c-3,linux
来源: https://codeday.me/bug/20191210/2100576.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有