Inter-Process Communication

a message queue

A pipe hands you a raw stream of bytes with no edges — you cannot tell where one message ends and the next begins. Sometimes you want the opposite: drop in a whole message, and have the receiver pull out exactly that message, intact, as one unit. A message queue is a kernel-managed mailbox that preserves these boundaries. You put a discrete message in; the reader takes a discrete message out. The grouping is kept.

There are two flavors. System V message queues (older) are created with msgget() and used with msgsnd() and msgrcv(); each message carries a 'type' field, an integer you can use to selectively receive only messages of a given type — a small built-in routing trick. POSIX message queues (newer, often nicer) are opened by name with mq_open() (the name looks like /myqueue), sent with mq_send(), received with mq_receive(), and they add message priorities (higher-priority messages are delivered first) and the option to get notified when a message arrives. In both, the kernel stores the queued messages, so a message survives even if the sender exits before the receiver reads it — unlike a signal, which is gone once handled.

Message queues shine when you want message-passing semantics: clean, framed, prioritized, asynchronous handoffs between processes on one machine, without inventing your own framing on top of a pipe. The honest limits: queues have a finite capacity, so a full queue makes mq_send() block (or fail if non-blocking) — backpressure again. System V queues persist until explicitly removed and are addressed by awkward numeric keys; POSIX queues live under a name and must be unlinked. And for talking across machines you would not use these at all — a real network message broker or sockets is the tool. These are local IPC.

mqd_t q = mq_open("/jobs", O_CREAT|O_WRONLY, 0600, NULL); mq_send(q, "build #7", 8, 5); /* one whole message, priority 5 */ /* the reader's mq_receive() gets exactly "build #7", boundaries intact */

Unlike a pipe, a queue preserves message edges and (POSIX) priority. The kernel holds the messages until read.

Message queues preserve boundaries (one send = one receive), which pipes do not. But they are still local-machine IPC with a fixed capacity — a full queue blocks the sender, and persistence means you must remove the queue yourself.

Also called
System V message queuePOSIX message queuemq訊息佇列