๐Ÿง  What is Message Passing?

Message Passing is an IPC mechanism where processes communicate by sending and receiving discrete messages through the OS or network โ€” without sharing memory.

Each message acts like a letter โ€” the sender drops it off, the receiver picks it up.
No direct memory access is involved.


๐Ÿ“ฆ Characteristics of Message Passing

FeatureDescription
๐Ÿ“ฎ No shared memoryEach process has isolated address space
๐Ÿ” Explicit communicationSend/receive operations required
๐Ÿง  OS-managed synchronizationOS ensures message delivery order (to some extent)
๐Ÿ›ก๏ธ Safe by designLess prone to data races (compared to shared memory)
๐ŸŒ Supports distributed systemsWorks across different machines (e.g., over sockets)

๐Ÿ” Message Passing Flow

[Process A] -- send(msg) --> [ Kernel or Network ] -- recv(msg) --> [Process B]

The kernel (or message server) acts like the post office.


๐Ÿงฐ Types of Message Passing Mechanisms

1. ๐Ÿงต Pipes

  • Unidirectional or bidirectional

  • Only between related processes (like parent-child)

2. ๐Ÿ“› Named Pipes (FIFOs)

  • Can work between unrelated processes

  • Exists in filesystem as a special file

3. ๐Ÿ“จ Message Queues

  • OS-managed queue with message buffers

  • Processes enqueue/dequeue structured messages

4. ๐ŸŒ Sockets

  • For network communication (TCP/UDP)

  • Used in client-server architecture (e.g., HTTP, WebSocket)


๐Ÿ“š Synchronous vs Asynchronous Message Passing

TypeBehavior
โณ Blocking (Synchronous)Sender waits until receiver acknowledges
๐Ÿงญ Non-Blocking (Asynchronous)Sender continues immediately after sending

Blocking provides tight coordination, but reduces concurrency.
Non-blocking improves throughput, but needs more complex logic.


๐Ÿ” Code Example (POSIX Message Queue - simplified)

mqd_t mq = mq_open("/myqueue", O_CREAT | O_RDWR, 0666, NULL);
mq_send(mq, "Hello", 6, 0);  // Sender
mq_receive(mq, buffer, sizeof(buffer), NULL);  // Receiver

โš™๏ธ Real-Life Analogy

Imagine two people in different rooms using walkie-talkies or email.
They canโ€™t see each otherโ€™s notes (memory), but they can talk or send messages back and forth.


๐Ÿ”„ Message Passing vs Shared Memory

FeatureMessage PassingShared Memory
๐Ÿ”— CouplingLoose (safe)Tight (risk of race conditions)
๐Ÿš€ PerformanceSlower (kernel mediation)Faster (direct access)
โš™๏ธ SynchronizationBuilt-in (implicit)Manual (use semaphores)
๐Ÿ“ฆ Use CaseDistributed systems, microservicesHigh-speed local IPC

๐Ÿง  Interview-Ready Definition:

Message Passing is an IPC mechanism in which processes communicate by sending and receiving messages, without sharing memory. Itโ€™s managed by the OS and ensures safe communication, making it ideal for isolated processes and distributed systems.