POSIX message queues
Exchange discrete, prioritised messages between processes.
By Invicly Tech, , in Linux System Programming. About 10 minutes to read.
In short
POSIX message queues carry discrete messages with priorities, so the reader always receives whole messages and the highest priority first. Unlike pipes, they keep message boundaries and exist independently of any process until unlinked. They suit passing small commands or jobs between processes.
Explained simply
A message queue is like a mailbox kept by the kernel. A process drops in a whole message, and another process takes out a whole message. Unlike a pipe, which is a stream of bytes with no edges, a queue always keeps each message separate.
Each message also has a priority number. When a reader takes a message, it always gets the one with the highest priority, and among equal priorities, the oldest one. So an "urgent" job can jump ahead of routine work.
A queue has a name such as /jobs and keeps existing even when no program has it open, until someone removes it. A producer can fill it now and a consumer can read it later, as long as the machine stays up.
Queues are best for small messages: commands, job IDs or short status updates. For big data, shared memory is faster; for a stream of bytes, a pipe or socket is simpler.
Press Play on a diagram to walk through it one step at a time.
- 1mq_open
Create /jobs with mq_maxmsg and mq_msgsize.
- 2mq_send
Producer sends a message with a priority.
- 3Kernel queue
Ordered by priority, then by arrival.
- 4mq_receive
Consumer gets the oldest highest-priority message.
- 5mq_unlink
Remove the queue name when finished.
- Producer to Queue /jobs: send "resize photo" priority 11send "resize photo" priority 1
- Producer to Queue /jobs: send "send invoice" priority 12send "send invoice" priority 1
- Producer to Queue /jobs: send "reset password" priority 93send "reset password" priority 9
- Consumer to Queue /jobs: mq_receive4mq_receive
- Queue /jobs to Consumer: "reset password" (highest first)5"reset password" (highest first)
- Queue /jobs to Consumer: then "resize photo" (oldest of priority 1)6then "resize photo" (oldest of priority 1)
- Byte stream, no boundaries
- Strict arrival order
- Gone when all ends close
- Best for streaming data
- Whole messages kept separate
- Priority ordering
- Persists until mq_unlink
- Best for small jobs and commands
- No copying
- You define the structure
- You add all locking
- Best for large or frequent data
In depth
Attributes and system limits
Every queue has two fixed attributes chosen at mq_open: mq_maxmsg, how many messages it can hold, and mq_msgsize, the largest message in bytes. If you pass NULL, Linux uses the defaults in /proc/sys/fs/mqueue/msg_default (10) and msgsize_default (8192). Unprivileged processes may not exceed msg_max (10 by default) and msgsize_max (8192 by default); asking for more fails with EINVAL. queues_max limits how many queues exist in total (256 by default).
The memory a user's queues can reserve is capped by the RLIMIT_MSGQUEUE resource limit, 819200 bytes by default, so very large queues need a raised limit. mq_getattr reads the attributes and the current message count (mq_curmsgs). mq_setattr can only change the O_NONBLOCK flag; size limits are fixed for the queue's lifetime.
- sysctl fs.mqueue.msg_max shows the per-queue cap
- ulimit -q shows the message queue byte limit
- Link with -lrt on systems whose glibc needs it
Blocking, timeouts and polling
mq_send blocks while the queue is full; mq_receive blocks while it is empty. Open with O_NONBLOCK and both return -1 with EAGAIN instead. mq_timedsend and mq_timedreceive take an absolute deadline on CLOCK_REALTIME and fail with ETIMEDOUT when it passes, so compute it as now plus your timeout.
Priorities run from 0 up to sysconf(_SC_MQ_PRIO_MAX) minus 1, which is 32767 on Linux. The receive buffer must be at least mq_msgsize bytes, or mq_receive fails with EMSGSIZE, even if the waiting message is tiny. On Linux an mqd_t is a real file descriptor, so you can add a queue to poll or epoll and treat "message waiting" as just another event in your loop.
mq_notify: being told when mail arrives
mq_notify registers the calling process to be notified when a message lands in an empty queue. The notification can be a signal (SIGEV_SIGNAL) or a function started in a new thread (SIGEV_THREAD). It is one-shot: after it fires you must register again, and you should drain the queue first, because further messages in a non-empty queue do not notify.
Only one process can be registered per queue, and no notification is sent if another process is already blocked in mq_receive, because that process gets the message directly. These rules make mq_notify easy to get wrong. On Linux, putting the queue descriptor into epoll is usually simpler and more predictable.
The mqueue file system and cleanup
Linux shows queues as files in a special file system mounted at /dev/mqueue (mount -t mqueue none /dev/mqueue if it is missing). cat /dev/mqueue/jobs prints a line such as QSIZE:129 NOTIFY:0 SIGNO:0 NOTIFY_PID:0, where QSIZE is the total bytes of queued messages. ls -l shows the owner and permissions, which control who may open the queue.
A queue lives until mq_unlink or reboot. Like files, unlinking removes the name at once, while processes that already have it open keep using it until they close it. Long-running services should unlink stale queues at startup or use O_EXCL to detect leftovers. Inside containers, queues are separated by the IPC namespace.
- 1mq_open O_CREAT
Appears as /dev/mqueue/jobs.
- 2Producers send
Blocks or EAGAIN when full.
- 3Consumers receive
Highest priority, oldest first.
- 4mq_close
Each process releases its handle.
- 5mq_unlink
Name removed; freed after last close.
Learn it in 4 short steps
About 40m each. Track them with a timer in your plan.
- 1Open a queue with mq_open~40m
- 2Send and receive with priorities~40m
- 3Set queue attributes and limits~40m
- 4Compare with pipes and shared memory~40m
Key points
- Each message is delivered whole; boundaries are preserved.
- Messages with higher priority numbers are received first.
- mq_receive needs a buffer at least mq_msgsize bytes long.
- System-wide limits live in /proc/sys/fs/mqueue.
Key terms
Tap a card to flip it. 0/5 known
Examples
#include <fcntl.h>
#include <mqueue.h>
#include <stdio.h>
int main(void) {
struct mq_attr attr = { .mq_maxmsg = 10, .mq_msgsize = 128 };
mqd_t q = mq_open("/jobs", O_CREAT | O_RDWR, 0600, &attr);
if (q == (mqd_t)-1) { perror("mq_open"); return 1; }
mq_send(q, "low", 4, 1);
mq_send(q, "urgent", 7, 9);
char buf[128]; unsigned prio;
mq_receive(q, buf, sizeof buf, &prio);
printf("%s (priority %u)\n", buf, prio); // urgent comes first
mq_close(q); mq_unlink("/jobs");
return 0;
}Priority 9 is received before priority 1.
A job consumer that sizes its buffer correctly
The consumer does not know the queue's message size in advance. Step 1: open the existing queue read-only. Step 2: ask mq_getattr for mq_msgsize and allocate a buffer that large, which avoids EMSGSIZE. Step 3: loop on mq_receive and print each job with its priority. Step 4: stop when a job called quit arrives. Messages are sent with their terminating NUL here, so they print as strings.
#include <fcntl.h>
#include <mqueue.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
mqd_t q = mq_open("/jobs", O_RDONLY);
struct mq_attr a;
if (q == (mqd_t)-1 || mq_getattr(q, &a) < 0) { perror("mq"); return 1; }
char *buf = malloc((size_t)a.mq_msgsize); unsigned prio; ssize_t n;
if (!buf) return 1;
while ((n = mq_receive(q, buf, (size_t)a.mq_msgsize, &prio)) >= 0) {
printf("job %.*s (priority %u)\n", (int)n, buf, prio);
if (strcmp(buf, "quit") == 0) break;
}
free(buf); mq_close(q); return 0;
}Inspecting queues and limits from the shell
A producer reports EAGAIN or EINVAL and you want to know why. Step 1: list existing queues. Step 2: read one queue's status line to see how many bytes are waiting. Step 3: check the system caps that limit mq_maxmsg and mq_msgsize for normal users. Step 4: raise a cap for testing (as root), or delete a stale queue left by a crashed run.
ls -l /dev/mqueue
cat /dev/mqueue/jobs # QSIZE:... NOTIFY:0 SIGNO:0 NOTIFY_PID:0
sysctl fs.mqueue # msg_max, msgsize_max, queues_max ...
ulimit -q # bytes all your queues may reserve
sudo sysctl -w fs.mqueue.msg_max=100
rm /dev/mqueue/jobs # same as mq_unlink("/jobs")Quick reference
- mq_open("/name", O_CREAT | O_RDWR, 0600, &attr) creates a queue
- The receive buffer must be at least mq_msgsize bytes or you get EMSGSIZE
- Higher priority numbers are received first; equal priorities come in FIFO order
- Defaults: 10 messages of 8192 bytes; caps in /proc/sys/fs/mqueue
- mq_timedreceive takes an absolute CLOCK_REALTIME deadline
- On Linux an mqd_t is a file descriptor you can poll or epoll
- Queues appear in /dev/mqueue; remove one with mq_unlink or rm
Common mistakes
- Passing a receive buffer smaller than mq_msgsize, which fails with EMSGSIZE.
- Forgetting mq_unlink, so the queue lingers in /dev/mqueue after the program exits.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a queue with room for 5 messages of 64 bytes, send 3 messages, and print mq_curmsgs from mq_getattr.
- Exercise 2medium
Write a receiver that waits at most 2 seconds for a message and prints "timeout" if none arrives.
- Exercise 3hard
Add a message queue to an epoll loop next to stdin, so the program handles typed lines and queued messages in the same loop.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between POSIX and System V message queues?
- POSIX queues (mq_open) use names and file descriptors and have a simpler API. System V queues (msgget) use numeric keys and message types, and are listed with ipcs -q.
- Do message queues survive a reboot?
- No. They live in kernel memory and persist only until mq_unlink or a reboot.
- Are message queues good for large data?
- Not really; each message is copied into and out of the kernel and sizes are capped. Send a small reference instead and keep the data in shared memory or a file.