通过共享内存进行进程间通信与 Mach 中使用的消息传递 OS

Inter-process communication via shared memory vs message passing used in Mach OS

以下段落来自 操作系统概念,第 10 版,作者 A​​braham Silberschatz pg。 138;

The major problem with message systems has generally been poor performance caused by copying of messages from the sender’s port to the receiver’s port. The Mach message system attempts to avoid copy operations by using virtual-memory-management techniques (Chapter 10). Essentially, Mach maps the address space containing the sender’s message into the receiver’s address space. Therefore, the message itself is never actually copied, as both the sender and receiver access the same memory. This message-management technique provides a large performance boost but works only for intrasystem messages.

本节通过 Mach 中的消息传递解释 ipc OS。然而,我很困惑这与 ipc 的共享内存模型有何不同,因为在幕后,发送方和接收方进程似乎共享 ipc 的一段内存。对此进行讨论将非常有帮助。谢谢

However I'm confused how this is different from the shared memory model of ipc since, under the hood, it appears that both the sender and receiver processes share a segment of memory for ipc.

他们的消息传递确实在常见情况下使用共享内存;然而,仅共享内存是不够的,因为它缺乏与调度程序的任何协作。具体来说,如果一个任务需要等到消息到达,调度程序被告知“不要给这个任务任何 CPU 时间 until/unless 消息到达(并且调度程序立即切换到另一个任务)”,然后当发送方发送消息(通过共享内存)时,它还必须告诉调度程序“嘿,如果接收方正在等待消息,那么它可以停止等待并再次获得 CPU 时间!”。

单独使用纯共享内存(不与调度程序合作)你最终会遇到数百个任务,不断轮询它们的所有消息端口,白白浪费大量 CPU 时间(并削弱所有有用工作的表现)。

请注意,使用共享内存进行消息传递(以及将共享内存用于其他类型的 IPC)还有另一个问题。如果恶意发送者有可能在接收者检查数据正常之后但在接收者对该数据采取行动之前修改数据;然后发送方可以欺骗接收方做接收方不允许的事情;你最终会面临重大的安全风险。我不知道 Mach 是否采取了任何措施来解决这个问题(理论上内核可以临时修改发送方的虚拟内存以防止它在接收方完全处理完数据之前修改共享内存中的“已发送”数据,但是性能所涉及的含义并且没有简单的方法可以告诉 if/when 接收方实际上已经完全完成了数据)。