A priority message queue
Deliver the highest-priority message first, and FIFO within a priority. A medium embedded C problem (Linux IPC mechanisms), run and graded in the browser.
medium · Linux IPC mechanisms · linux · ipc · queues
A POSIX message queue (mq_send / mq_receive) delivers messages by priority: the highest priority first, and messages of equal priority in the order they were sent. A full queue rejects new messages (with a non-blocking queue: EAGAIN).
Write mq_send_msg(q, text, prio), returning 0 or -1 if full, and mq_receive_msg(q, out, prio), which copies the next message's text (at most 15 characters) and priority and returns 0, or -1 if the queue is empty.
Starter code
int mq_send_msg(mq_t *q, const char *text, unsigned prio) {
strncpy(q->msgs[q->count].text, text, 15);
q->msgs[q->count].prio = prio;
q->count++;
return 0;
}
int mq_receive_msg(mq_t *q, char *out, unsigned *prio) {
if (q->count == 0) return -1;
q->count--;
strcpy(out, q->msgs[q->count].text);
*prio = q->msgs[q->count].prio;
return 0;
}Example tests
Priorities
mq_t q = {0};
mq_send_msg(&q, "log", 1);
mq_send_msg(&q, "alarm", 9);
mq_send_msg(&q, "status", 5);
drain(&q);Expected output:
alarm(9) status(5) log(1)FIFO within a priority
mq_t q = {0};
mq_send_msg(&q, "a", 3);
mq_send_msg(&q, "b", 3);
mq_send_msg(&q, "urgent", 7);
mq_send_msg(&q, "c", 3);
drain(&q);Expected output:
urgent(7) a(3) b(3) c(3)Learn it first
- Linux IPC mechanisms · Pipes, shared memory, sockets, message queues, signals and D-Bus.