如何安全删除 boost::shared_memory_object
我正在为 IPC 使用 boost::shared_memory_object 。我有一个客户端和服务器。我使用两个消息队列。一种用于向服务器发送请求,另一种用于接收服务器的回复。它是一个异步协议。我的问题是我不知道如何在发生故障时安全地删除共享内存对象。考虑这样的场景:
- 服务器启动
- 客户端启动并连接到服务器;消息队列是在共享内存中创建的。
- 客户端定期向服务器发送心跳;一切都好。
- 客户因处理过多而受阻;错过一些心跳
- 服务器认为客户端已死亡,清理队列(shared_memory_object::remove 将删除队列,即使存在一个正在运行的进程,并且该共享内存段的句柄已打开)
- 客户端完成处理;尝试写入已删除的消息队列:
这里一切都乱了。有时写入成功,有时崩溃。谁知道消息队列被删除后,其他进程是否在同一内存地址上创建了新的共享内存对象......
显然,如果客户端认为服务器已关闭并删除了队列,那么服务器线程尝试读取/写入队列可能会崩溃(或损坏内存)。
I am using a boost::shared_memory_object for IPC. I have a client and server. I use two message queues. One for sending requests to the server and one for receiving replies from the server. It is an asynchronous protocol. My problem is that I do not know how to safely remove the shared_memory_objects in case of failures. Consider this scenario:
- Server starts
- Client starts and connects to server; message queues are created in shared memory.
- Client sends regular heartbeats to server; everything is ok.
- Client gets held up with too much processing; misses some heartbeats
- Server thinks client is dead, cleans up the queues (shared_memory_object::remove will remove the queue even if there is a running process with a handle to that shared memory segment open)
- Client finishes processing; tries to write to message queue that has been deleted:
All hell breaks loose here. Sometimes the write succeeds, sometimes it crashes. Who knows whether other process, after the message queue has been deleted, have created new shared memory objects on the same memory address...
Clearly, if the client thinks that the server is down and it deletes the queue, then the server thread that tries to read/write to the queue might crash (or corrupt memory).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论