๐ง 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
| Feature | Description |
|---|---|
| ๐ฎ No shared memory | Each process has isolated address space |
| ๐ Explicit communication | Send/receive operations required |
| ๐ง OS-managed synchronization | OS ensures message delivery order (to some extent) |
| ๐ก๏ธ Safe by design | Less prone to data races (compared to shared memory) |
| ๐ Supports distributed systems | Works 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
| Type | Behavior |
|---|---|
| โณ 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
| Feature | Message Passing | Shared Memory |
|---|---|---|
| ๐ Coupling | Loose (safe) | Tight (risk of race conditions) |
| ๐ Performance | Slower (kernel mediation) | Faster (direct access) |
| โ๏ธ Synchronization | Built-in (implicit) | Manual (use semaphores) |
| ๐ฆ Use Case | Distributed systems, microservices | High-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.