Message Queues
Understand how message queues preserve message boundaries, allow asynchronous communication, and are often easier to manage than shared memory for structured data transfer.
We'll cover the following...
Message queues provide a different model of communication from both pipes and shared memory.
Instead of sharing memory or sending raw byte streams, message queues allow processes to exchange discrete messages. Each message is treated as a complete unit, preserving its boundaries. This makes communication more structured and often easier to manage when transferring well-defined pieces of data.
What is a message queue?
A message queue is a kernel-managed data structure that stores messages until they are retrieved by another process. Unlike pipes, which treat data as a continuous stream of bytes, message queues preserve message boundaries. When a process receives data from a message queue, it retrieves exactly one complete message at a time.
Message queues also support asynchronous communication. The sending process and receiving process do not need to run at the same time. Messages remain in the queue until they are read.
In POSIX systems, message queues are accessed using functions declared in <mqueue.h>.
Creating and opening a message queue
A POSIX message queue is created or opened using mq_open():