Skip to content
systemcoding.dev
Systems Programming

Send Messages Between Processes with POSIX mq_send and mq_receive

Send and receive messages between processes with POSIX message queues: mq_open, priorities, the mq_receive buffer rule, limits and cleanup on Linux 6.12.

6 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, Rust and GNU logos.

A pipe moves bytes, and you decide where one message ends. A POSIX message queue moves whole messages, keeps them in order of priority and holds them in the kernel until someone reads them, even if the reader has not started yet. This post sends and receives messages with mq_open(), mq_send() and mq_receive() on Linux 6.12 with glibc 2.41, following mq_overview(7), mq_open(3) and the POSIX mq_send page.

For how queues compare with pipes and sockets, see IPC mechanisms compared. The older System V interface is covered in use System V message queues with msgsnd and msgrcv, and POSIX IPC vs System V IPC explains when to pick which.

What a POSIX message queue is

A queue is a kernel object with a name that starts with a slash, such as /jobs. Any process that knows the name can open it. Each message is a block of bytes with a priority from 0 up to at least 31. mq_receive() always returns the oldest message with the highest priority, so urgent messages overtake routine ones, and equal priorities come out in the order they were sent.

The queue has two limits fixed when it is created, held in struct mq_attr:

FieldMeaning
mq_maxmsgThe most messages the queue holds at once
mq_msgsizeThe largest single message, in bytes

Flow control follows from these. A sender to a full queue blocks, or gets EAGAIN if the queue is nonblocking. A receiver on an empty queue blocks the same way. The queue's descriptor, type mqd_t, is a real file descriptor on Linux, so poll(), select() and epoll work on it.

A first program

This program creates a queue, sends three messages with different priorities and reads them back.

mq_demo.cc
#include <fcntl.h>
#include <mqueue.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

#define QNAME "/demo_jobs"

int main(void)
{
    struct mq_attr attr = { .mq_flags = 0, .mq_maxmsg = 8, .mq_msgsize = 64 };
    char buf[64];
    unsigned prio;
    mqd_t q;
    ssize_t n;

    q = mq_open(QNAME, O_CREAT | O_RDWR, 0600, &attr);
    if (q == (mqd_t)-1) {
        perror("mq_open");
        return 1;
    }

    mq_send(q, "low priority backup", strlen("low priority backup"), 1);
    mq_send(q, "routine report", strlen("routine report"), 5);
    mq_send(q, "urgent alert", strlen("urgent alert"), 20);

    mq_getattr(q, &attr);
    printf("queued: %ld messages\n", attr.mq_curmsgs);

    for (int i = 0; i < 3; i++) {
        n = mq_receive(q, buf, sizeof buf, &prio);
        if (n == -1) {
            perror("mq_receive");
            return 1;
        }
        buf[n] = '\0';
        printf("priority %2u: %s\n", prio, buf);
    }

    mq_close(q);
    mq_unlink(QNAME);
    return 0;
}
Text
queued: 3 messages
priority 20: urgent alert
priority  5: routine report
priority  1: low priority backup

The messages were sent in the order low, routine, urgent, and they came out in the opposite order because priority decides. The mq_unlink() at the end removes the name, so the next run starts clean. On older glibc releases you had to link with -lrt, and since glibc 2.34 the functions are in the main library.

The receive buffer rule

mq_receive() has a rule that trips almost everyone once: **the buffer you pass must be at least as large as the queue's mq_msgsize**, not just as large as the message you expect. If it is smaller, the call fails with EMSGSIZE and the message stays queued.

small_buf.cc
char tiny[8];
ssize_t n = mq_receive(q, tiny, sizeof tiny, NULL);
if (n == -1)
    perror("mq_receive");
Text
mq_receive: Message too long

The fix is to size the buffer from the queue's attributes, which you can read with mq_getattr(), or to use the same constant you used to create the queue.

getattr.cc
struct mq_attr a;
mq_getattr(q, &a);
char *buf = malloc((size_t)a.mq_msgsize);

The return value is the length of the message, which can be much less than mq_msgsize. Messages are not NUL-terminated by the queue, so add the terminator yourself, as the program does, or treat the data as bytes.

A sender and a receiver as separate programs

The usual use is two programs. The sender creates or opens the queue and sends. The receiver opens it and loops.

sender.cc
#include <fcntl.h>
#include <mqueue.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    mqd_t q = mq_open("/demo_jobs", O_WRONLY);

    if (q == (mqd_t)-1) {
        perror("mq_open");
        return 1;
    }
    for (int i = 1; i < argc; i++) {
        if (mq_send(q, argv[i], strlen(argv[i]), 10) == -1) {
            perror("mq_send");
            return 1;
        }
    }
    mq_close(q);
    return 0;
}
receiver.cc
#include <fcntl.h>
#include <mqueue.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int main(void)
{
    struct mq_attr attr = { .mq_maxmsg = 8, .mq_msgsize = 128 };
    mqd_t q = mq_open("/demo_jobs", O_CREAT | O_RDONLY, 0600, &attr);
    char *buf;

    if (q == (mqd_t)-1) {
        perror("mq_open");
        return 1;
    }
    mq_getattr(q, &attr);
    buf = malloc((size_t)attr.mq_msgsize + 1);

    for (;;) {
        ssize_t n = mq_receive(q, buf, (size_t)attr.mq_msgsize, NULL);
        if (n == -1) {
            perror("mq_receive");
            break;
        }
        buf[n] = '\0';
        printf("job: %s\n", buf);
        if (strcmp(buf, "quit") == 0)
            break;
    }
    mq_close(q);
    mq_unlink("/demo_jobs");
    return 0;
}

Start the receiver. It creates the queue and waits. In another terminal, run ./sender build deploy quit:

Text
job: build
job: deploy
job: quit

The receiver exits after quit. The sender could also run first: its mq_open() without O_CREAT would fail with ENOENT because the queue does not exist yet, so decide which side creates it, or have both pass O_CREAT with the same attributes.

Limits and errors

Linux bounds queues through files under /proc/sys/fs/mqueue/. msg_max is the largest mq_maxmsg an unprivileged process can request (10 by default), msgsize_max is the largest mq_msgsize (8,192 by default) and queues_max is the system-wide number of queues (256). Beyond these, mq_open() with attributes fails with EINVAL. Per-user memory is also limited by RLIMIT_MSGQUEUE, 819,200 bytes by default, and exceeding it gives EMFILE on create. Passing a null attribute pointer to mq_open() takes the defaults, which are mq_maxmsg of 10 and mq_msgsize of 8,192, and that queue costs about 80 KiB of the user's limit.

Other errors to expect: EAGAIN from mq_send() on a full nonblocking queue, EMSGSIZE from mq_send() when the message exceeds mq_msgsize, EBADF from using a descriptor opened with the wrong access mode, and EEXIST for O_CREAT | O_EXCL on an existing name.

Timeouts and waking up

mq_timedsend() and mq_timedreceive() take an absolute deadline measured on CLOCK_REALTIME and fail with ETIMEDOUT when it passes. For event-driven programs, add the descriptor to epoll: the queue is readable when a message waits. POSIX also defines mq_notify(), which asks the kernel to deliver a signal or start a thread when a message arrives at an empty queue. It is a one-shot registration, and you register again after each notification, which makes epoll simpler in most designs.

Inspecting from the shell

Mount the queue filesystem to see queues as files, with mount -t mqueue none /dev/mqueue, which many systems do at boot. ls /dev/mqueue lists names, and cat /dev/mqueue/demo_jobs prints the queue's state, including QSIZE (bytes queued), and the notification settings.

Shell
cat /dev/mqueue/demo_jobs
Text
QSIZE:45         NOTIFY:0     SIGNO:0     NOTIFY_PID:0

The QSIZE value is the total bytes of the messages waiting, which would be 45 for the three messages sent in the first program if they had been left unread: 19, 14 and 12 characters, with no terminators sent.

When not to use a message queue

Skip it if you need many clients with two-way conversations, where a Unix socket gives each client its own connection. A message queue has no concept of sender identity, so replies need a second queue per client. It also is not for large payloads: the 8 KiB default message size is a signal to use shared memory for bulk data and send only a reference. And on systems without the mqueue filesystem or in locked-down containers it may be unavailable, so be prepared for ENOSYS.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.