共享内存:位置和锁定策略
我有一个创建共享内存区域的编写器,我想确保读取器在编写器准备好之前无法 shm_open() 该区域。我的做法是,作者将以只读模式 shm_open 。一旦正确构建了该区域,我就 chmod() 该文件。这太糟糕了,我无法 fcntl() 文件描述符来更改权限。有什么建议吗(除了在该区域进行一些糟糕的同步之外?)
为什么 chmod() 令人讨厌?部分原因是没有 glibc 代码(即公开的)来告诉我共享内存区域位于何处(例如 /dev/shm)。 glibc 中有一些代码可以查看安装,我不想复制它,但如果没有人能给我比 chmod() 更好的解决方案,我可能别无选择。
I have a writer that creates a shared memory region, I'd like to ensure that readers fail to shm_open() the region until the writer is ready. My hacky way of doing this is writer will shm_open in read-only mode. Once the region is correctly constructed I chmod() the file. This is yucky, and I cannot fcntl() the file descriptor to change the permissions. Any suggestions (short of doing some awful sync in the region?)
Why is chmod() yucky? Partly because there is no glibc code (exposed that is) to tell me where the shared memory region lives (eg /dev/shm). There is some code in glibc to look through the mounts, I'd prefer not to copy it but might have no choice if noone can give me a better solution than the chmod().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了使用 shm_open,您当然可以使用 mmap - 这允许您使用您选择的目录中的文件(也许这是将其放在 ramdisc 上的优化)。
但为了解决锁定问题,也许您应该在共享区域中使用互斥体,或者(在推送时)只flock()文件。
然而,如果您试图使其表现为队列,也许您应该使用更多队列类型的 IPC 对象。
Instead of using shm_open, you can certainly use mmap - this allows you to use a file in a directory of your choice (maybe it is an optimisation to place this on a ramdisc).
But to solve the locking problem, maybe you should use a mutex in the shared region, or (at a push) just flock() the file.
If you are trying to make it behave as a queue however, maybe you should just use a more queue-type IPC object instead.