MQ_OVERVIEW(7) Linux Programmer’s Manual MQ_OVERVIEW(7) NAME mq_overview - Overview of POSIX message queues DESCRIPTION POSIX message queues allow processes to exchange data in the form of messages. This API is distinct from that provided by System V message queues (msgget(2), msgsnd(2), msgrcv(2), etc.), but provides similar functionality. Message queues are created and opened using mq_open(3); this function returns a message queue descriptor (mqd_t), which is used to refer to the open message queue in later calls. Each message queue is identi‐ fied by a name of the form /somename. Two processes can operate on the same queue by passing the same name to mq_open(). Messages are transferred to and from a queue using mq_send(3) and mq_receive(3). When a process has finished using the queue, it closes it using mq_close(3), and when the queue is no longer required, it can be deleted using mq_unlink(3). Queue attributes can be retrieved and (in some cases) modified using mq_getattr(3) and mq_setattr(3). A pro‐ cess can request asynchronous notification of the arrival of a message on a previously empty queue using mq_notify(3). A message queue descriptor is a reference to an open message queue description (cf. open(2)). After a fork(2), a child inherits copies of its parent’s message queue descriptors, and these descriptors refer to the same open message queue descriptions as the corresponding descriptors in the parent. Corresponding descriptors in the two pro‐ cesses share the flags (mq_flags) that are associated with the open message queue description. Each message has an associated priority, and messages are always deliv‐ ered to the receiving process highest priority first. Message priori‐ ties range from 0 (low) to sysconf(_SC_MQ_PRIO_MAX) - 1 (high). On Linux, sysconf(_SC_MQ_PRIO_MAX) returns 32768, but POSIX.1-2001 only requires an implementation to support priorities in the range 0 to 31; some implementations only provide this range. Library interfaces and system calls In most cases the mq_*() library interfaces listed above are imple‐ mented on top of underlying system calls of the same name. Deviations from this scheme are indicated in the following table: Library interface System call mq_close(3) close(2) mq_getattr(3) mq_getsetattr(2) mq_open(3) mq_open(2) mq_receive(3) mq_timedreceive(2) mq_send(3) mq_timedsend(2) mq_setattr(3) mq_getsetattr(2) mq_timedreceive(3) mq_timedreceive(2) mq_timedsend(3) mq_timedsend(2) mq_unlink(3) mq_unlink(2) LINUX SPECIFIC DETAILS Versions POSIX message queues have been supported on Linux since kernel 2.6.6. Glibc support has been provided since version 2.3.4. Kernel configuration Support for POSIX message queues is configurable via the CON‐ FIG_POSIX_MQUEUE kernel configuration option. This option is enabled by default. Persistence POSIX message queues have kernel persistence: if not removed by mq_unlink(), a message queue will exist until the system is shut down. Linking Programs using the POSIX message queue API must be compiled with cc -lrt to link against the real-time library, librt. /proc interfaces The following interfaces can be used to limit the amount of kernel mem‐ ory consumed by POSIX message queues: /proc/sys/fs/mqueue/msg_max This file can be used to view and change the ceiling value for the maximum number of messages in a queue. This value acts as a ceiling on the attr->mq_maxmsg argument given to mq_open(3). The default and minimum value for msg_max is 10; the upper limit is HARD_MAX: (131072 / sizeof(void *)) (32768 on Linux/86). This limit is ignored for privileged processes (CAP_SYS_RESOURCE), but the HARD_MAX ceiling is nevertheless imposed. /proc/sys/fs/mqueue/msgsize_max This file can be used to view and change the ceiling on the max‐ imum message size. This value acts as a ceiling on the attr->mq_msgsize argument given to mq_open(3). The default and minimum value for msgsize_max is 8192 bytes; the upper limit is INT_MAX (2147483647 on Linux/86). This limit is ignored for privileged processes (CAP_SYS_RESOURCE). /proc/sys/fs/mqueue/queues_max This file can be used to view and change the system-wide limit on the number of message queues that can be created. Only priv‐ ileged processes (CAP_SYS_RESOURCE) can create new message queues once this limit has been reached. The default value for queues_max is 256; it can be changed to any value in the range 0 to INT_MAX. Resource limit The RLIMIT_MSGQUEUE resource limit, which places a limit on the amount of space that can be consumed by all of the message queues belonging to a process’s real user ID, is described in getrlimit(2). Mounting the message queue file system On Linux, message queues are created in a virtual file system. (Other implementations may also provide such a feature, but the details are likely to differ.) This file system can be mounted using the following commands: $ mkdir /dev/mqueue $ mount -t mqueue none /dev/mqueue The sticky bit is automatically enabled on the mount directory. After the file system has been mounted, the message queues on the sys‐ tem can be viewed and manipulated using the commands usually used for files (e.g., ls(1) and rm(1)). The contents of each file in the directory consist of a single line containing information about the queue: $ ls /dev/mqueue/mymq QSIZE:129 NOTIFY:2 SIGNO:0 NOTIFY_PID:8260 $ mount -t mqueue none /dev/mqueue These fields are as follows: QSIZE Number of bytes of data in all messages in the queue. NOTIFY_PID If this is non-zero, then the process with this PID has used mq_notify(3) to register for asynchronous message notification, and the remaining fields describe how notification occurs. NOTIFY Notification method: 0 is SIGEV_SIGNAL; 1 is SIGEV_NONE; and 2 is SIGEV_THREAD. SIGNO Signal number to be used for SIGEV_SIGNAL. Polling message queue descriptors On Linux, a message queue descriptor is actually a file descriptor, and can be monitored using select(2), poll(2), or epoll(7). This is not portable. CONFORMING TO POSIX.1-2001. NOTES System V message queues (msgget(2), msgsnd(2), msgrcv(2), etc.) are an older API for exchanging messages between processes. POSIX message queues provide a better designed interface than System V message queues; on the other hand POSIX message queues are less widely avail‐ able (especially on older systems) than System V message queues. EXAMPLE An example of the use of various message queue functions is shown in mq_notify(3). SEE ALSO getrlimit(2), mq_getsetattr(2), mq_close(3), mq_getattr(3), mq_notify(3), mq_open(3), mq_receive(3), mq_send(3), mq_unlink(3), poll(2), select(2), epoll(4) Linux 2.6.16 2006-02-25 MQ_OVERVIEW(7) MQ_OPEN(3) Linux Programmer’s Manual MQ_OPEN(3) NAME mq_open - open a message queue SYNOPSIS #include <mqueue.h> mqd_t mq_open(const char *name, int oflag); mqd_t mq_open(const char *name, int oflag, mode_t mode, struct mq_attr *attr); DESCRIPTION mq_open() creates a new POSIX message queue or opens an existing queue. The queue is identified by name. For details of the construction of name, see mq_overview(7). The oflag argument specifies flags that control the operation of the call. Exactly one of the following must be specified in oflag: O_RDONLY Open the queue to receive messages only. O_WRONLY Open the queue to send messages only. O_RDWR Open the queue to both send and receive messages. Zero or more of the following flags can additionally be ORed in oflag: O_NONBLOCK Open the queue in non-blocking mode. In circumstances where mq_receive() and mq_send() would normally block, these functions instead fail with the error EAGAIN. O_CREAT Create the message queue if it does not exist. The owner (user ID) of the message queue is set to the effective user ID of the calling process. The group ownership (group ID) is set to the effective group ID of the calling process. O_EXCL If O_CREAT was specified in oflag, and a queue with the given name already exists, then fail with the error EEXIST. If O_CREAT is specified in oflag, then two additional arguments must be supplied. The mode argument specifies the permissions to be placed on the new queue, as for open(2). The permissions settings are masked against the process umask. The attr argument specifies attributes for the queue. See mq_getattr(2) for details. If attr is NULL, then the queue is created with implementation-defined default attributes. RETURN VALUE On success, mq_open() returns a message queue descriptor for use by other message queue functions. On error, mq_open() returns (mqd_t) -1, with errno set to indicate the error. ERRORS EACCESS The queue exists, but the caller does not have permission to open it in the specified mode. EINVAL O_CREAT was specified in oflag, and attr was not NULL, but attr->mq_maxmsg or attr->mq_msqsize was invalid. Both of these fields must be greater than zero. In a process that is unprivi‐ leged (does not have the CAP_SYS_RESOURCE capability), attr->mq_maxmsg must be less than or equal to the msg_max limit, and attr->mq_msgsize must be less than or equal to the msg‐ size_max limit. In addition, even in a privileged process, attr->mq_maxmsg cannot exceed the HARD_MAX limit. (See mq_overview(7) for details of these limits.) EEXIST Both O_CREAT and O_EXCL were specified in oflag, but a queue with this name already exists. EMFILE The process already has the maximum number of files and message queues open. ENAMETOOLONG name was too long. ENFILE The system limit on the total number of open files and message queues has been reached. ENOENT The O_CREAT flag was not specified in oflag, and no queue with this name exists. ENOMEM Insufficient memory. ENOSPC Insufficient space for the creation of a new message queue. This probably occurred because the queues_max limit was encoun‐ tered; see mq_overview(7). CONFORMING TO POSIX.1-2001. BUGS In kernels before 2.6.14, the process umask was not applied to the per‐ missions specified in mode. SEE ALSO mq_close(3), mq_getattr(3), mq_notify(3), mq_receive(3), mq_send(3), mq_unlink(3), mq_overview(7) Linux 2.6.16 2006-02-25 MQ_OPEN(3) MQ_CLOSE(3) Linux Programmer’s Manual MQ_CLOSE(3) NAME mq_close - close a message queue descriptor SYNOPSIS #include <mqueue.h> mqd_t mq_close(mqd_t mqdes); DESCRIPTION mq_close() closes the message queue descriptor mqdes. If the calling process has attached a notification request to this mes‐ sage queue via mqdes, then this request is removed, and another process can now attach a notification request. NOTES All open message queues are automatically closed on process termina‐ tion, or upon execve(2). RETURN VALUE On success mq_close() returns 0; on error, -1 is returned, with errno set to indicate the error. ERRORS EBADF The descriptor specified in mqdes is invalid. CONFORMING TO POSIX.1-2001. SEE ALSO mq_getattr(3), mq_notify(3), mq_open(3), mq_receive(3), mq_send(3), mq_unlink(3), mq_overview(7) Linux 2.6.16 2006-02-25 MQ_CLOSE(3) MQ_SEND(3) Linux Programmer’s Manual MQ_SEND(3) NAME mq_send, mq_timedsend - send a message to a message queue SYNOPSIS #include <mqueue.h> mqd_t mq_send(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio); #define _XOPEN_SOURCE 600 #include <time.h> #include <mqueue.h> mqd_t mq_timedsend(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio, const struct timespec *abs_timeout); DESCRIPTION mq_send() adds the message pointed to by msg_ptr to the message queue referred to by the descriptor mqdes. The msg_len argument specifies the length of the message pointed to by msg_ptr; this length must be less than or equal to the queue’s mq_msgsize attribute. Zero-length messages are allowed. The msg_prio argument is a non-negative integer that specifies the pri‐ ority of this message. Messages are placed on the queue in decreasing order of priority, with newer messages of the same priority being placed after older messages with the same priority. If the message queue is already full (i.e., the number of messages on the queue equals the queue’s mq_maxmsg attribute), then, by default, mq_send() blocks until sufficient space becomes available to allow the message to be queued, or until the call is interrupted by a signal han‐ dler. If the O_NONBLOCK flag is enabled for the message queue descrip‐ tion, then the call instead fails immediately with the error EAGAIN. mq_timedsend() behaves just like mq_send(), except that if the queue is full and the O_NONBLOCK flag is not enabled for the message queue description, then abs_timeout points to a structure which specifies a ceiling on the time for which the call will block. This ceiling is an absolute timeout in seconds and nanoseconds since the Epoch (midnight on the morning of 1 January 1970), specified in the following struc‐ ture: struct timespec { time_t tv_sec; long tv_nsec; }; /* seconds */ /* nanoseconds */ If the message queue is full, and the timeout has already expired by the time of the call, mq_timedsend() returns immediately. RETURN VALUE On success, mq_send() and mq_timedsend() return zero; on error, -1 is returned, with errno set to indicate the error. ERRORS EAGAIN The queue was empty, and the O_NONBLOCK flag was set for the message queue description referred to by mqdes. EBADF The descriptor specified in mqdes was invalid. EMSGSIZE msg_len was greater than the mq_msgsize attribute of the message queue. EINTR The call was interrupted by a signal handler. EINVAL The call would have blocked, and abs_timeout was invalid, either because tv_sec was less than zero, or because tv_nsec was less than zero or greater than 1000 million. ETIMEDOUT The call timed out before a message could be transferred. CONFORMING TO POSIX.1-2001. SEE ALSO mq_close(3), mq_getattr(3), mq_notify(3), mq_open(3), mq_receive(3), mq_unlink(3), mq_overview(7) Linux 2.6.16 2006-02-25 MQ_SEND(3) MQ_RECEIVE(3) Linux Programmer’s Manual MQ_RECEIVE(3) NAME mq_receive, mq_timedreceive - receive a message from a message queue SYNOPSIS #include <mqueue.h> mqd_t mq_receive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio); #define _XOPEN_SOURCE 600 #include <time.h> #include <mqueue.h> mqd_t mq_timedreceive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio, const struct timespec *abs_timeout); DESCRIPTION mq_receive() removes the oldest message with the highest priority from the message queue referred to by the descriptor mqdes, and places it in the buffer pointed to by msg_ptr. The msg_len argument specifies the size of the buffer pointed to by msg_ptr; this must be greater than the mq_msgsize attribute of the queue (see mq_getattr(3)). If prio is not NULL, then the buffer to which it points is used to return the priority associated with the received message. If the queue is empty, then, by default, mq_receive() blocks until a message becomes available, or the call is interrupted by a signal han‐ dler. If the O_NONBLOCK flag is enabled for the message queue descrip‐ tion, then the call instead fails immediately with the error EAGAIN. mq_timedreceive() behaves just like mq_receive(), except that if the queue is empty and the O_NONBLOCK flag is not enabled for the message queue description, then abs_timeout points to a structure which speci‐ fies a ceiling on the time for which the call will block. This ceiling is an absolute timeout in seconds and nanoseconds since the Epoch (mid‐ night on the morning of 1 January 1970), specified in the following structure: struct timespec { time_t tv_sec; long tv_nsec; }; /* seconds */ /* nanoseconds */ If no message is available, and the timeout has already expired by the time of the call, mq_timedreceive() returns immediately. RETURN VALUE On success, mq_receive() and mq_timedreceive() return the number of bytes in the received message; on error, -1 is returned, with errno set to indicate the error. ERRORS EAGAIN The queue was empty, and the O_NONBLOCK flag was set for the message queue description referred to by mqdes. EBADF The descriptor specified in mqdes was invalid. EMSGSIZE msg_len was less than the mq_msgsize attribute of the message queue. EINTR The call was interrupted by a signal handler. EINVAL The call would have blocked, and abs_timeout was invalid, either because tv_sec was less than zero, or because tv_nsec was less than zero or greater than 1000 million. ETIMEDOUT The call timed out before a message could be transferred. CONFORMING TO POSIX.1-2001. SEE ALSO mq_close(3), mq_getattr(3), mq_notify(3), mq_open(3), mq_send(3), mq_unlink(3), mq_overview(7) Linux 2.6.16 2006-02-25 MQ_RECEIVE(3) MQ_NOTIFY(3) Linux Programmer’s Manual MQ_NOTIFY(3) NAME mq_notify - register for notification when a message is available SYNOPSIS #include <mqueue.h> mqd_t mq_notify(mqd_t mqdes, const struct sigevent *notification); DESCRIPTION mq_notify() allows the calling process to register or unregister for delivery of an asynchronous notification when a new message arrives on the empty message queue referred to by the descriptor mqdes. The notification argument is a pointer to a sigevent structure that is defined something like the following: union sigval { int sival_int; void *sival_ptr; }; /* Data passed with notification */ /* Integer value */ /* Pointer value */ struct sigevent { int sigev_notify; /* Notification method */ int sigev_signo; /* Notification signal */ union sigval sigev_value; /* Data passed with notification */ void (*sigev_notify_function) (union sigval); /* Function for thread notification */ void *sigev_notify_attributes; /* Thread function attributes */ }; If notification is a non-NULL pointer, then mq_notify() registers the calling process to receive message notification. The sigev_notify field of the sigevent to which notification points specifies how noti‐ fication is to be performed. This field has one of the following val‐ ues: SIGEV_NONE A "null" notification: the calling process is registered as the target for notification, but when a message arrives, no notifi‐ cation is sent. SIGEV_SIGNAL Notify the process by sending the signal specified in sigev_signo. If the signal is caught with a signal handler that was registered using the sigaction(2) SA_SIGINFO flag, then the following fields are set in the siginfo_t structure that is passed as the second argument of the handler: si_code is set to SI_MESGQ; si_signo is set to the signal number; si_value is set to the value specified in notification->sigev_value; si_pid is set to the PID of the process that sent the message; and si_uid is set to the real user ID of the sending process. The same information is available if the signal is accepted using sig‐ waitinfo(2). SIGEV_THREAD Deliver notification by invoking notifica‐ tion->sigev_thread_function as the start function of a new thread. The function is invoked with notification->sigev_value as its sole argument. If notification->sigev_notify_attributes is not NULL, then it should point to a pthread_attr_t structure that defines attributes for the thread. Only one process can be registered to receive notification from a mes‐ sage queue. If notification is NULL, and the calling process is currently regis‐ tered to receive notifications for this message queue, then the regis‐ tration is removed; another process can then register to receive a mes‐ sage notification for this queue. Message notification only occurs when a new message arrives and the queue was previously empty. If the queue was not empty at the time mq_notify() was called, then a notification will only occur after the queue is emptied and a new message arrives. If another process or thread is waiting to read a message from an empty queue using mq_receive(), then any message notification registration is ignored: the message is delivered to the process or thread calling mq_receive(), and the message notification registration remains in effect. Notification occurs once: after a notification is delivered, the noti‐ fication registration is removed, and another process can register for message notification. If the notified process wishes to receive the next notification, it can use mq_notify() to request a further notifi‐ cation. This should be done before emptying all unread messages from the queue. (Placing the queue in non-blocking mode is useful for emp‐ tying the queue of messages without blocking once it is empty.) RETURN VALUE On success mq_notify() returns 0; on error, -1 is returned, with errno set to indicate the error. ERRORS EBADF The descriptor specified in mqdes is invalid. EBUSY Another process has already registered to receive notification for this message queue. EINVAL notification->sigev_notify is not one of the permitted values; or notification->sigev_notify is SIGEV_SIGNAL and notifica‐ tion->sigev_signo is not a a valid signal number. ENOMEM Insufficient memory. CONFORMING TO POSIX.1-2001. EXAMPLE The following program registers a notification request for the message queue named in its command-line argument. Notification is performed by creating a thread. The thread executes a function which reads one mes‐ sage from the queue and then terminates the process. #include <pthread.h> #include <mqueue.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define die(msg) { perror(msg); exit(EXIT_FAILURE); } static void /* Thread start function */ tfunc(union sigval sv) { struct mq_attr attr; ssize_t nr; void *buf; mqd_t mqdes = *((mqd_t *) sv.sival_ptr); /* Determine max. msg size; allocate buffer to receive msg */ if (mq_getattr(mqdes, &attr) == -1) die("mq_getattr"); buf = malloc(attr.mq_msgsize); if (buf == NULL) die("malloc"); nr = mq_receive(mqdes, buf, attr.mq_msgsize, NULL); if (nr == -1) die("mq_receive"); printf("Read %ld bytes from MQ0, (long) nr); free(buf); exit(EXIT_SUCCESS); /* Terminate the process */ } int main(int argc, char *argv[]) { mqd_t mqdes; struct sigevent not; assert(argc == 2); mqdes = mq_open(argv[1], O_RDONLY); if (mqdes == (mqd_t) -1) die("mq_open"); not.sigev_notify = SIGEV_THREAD; not.sigev_notify_function = tfunc; not.sigev_notify_attributes = NULL; not.sigev_value.sival_ptr = &mqdes; /* Arg. to thread func. */ if (mq_notify(mqdes, &not) == -1) die("mq_notify"); pause(); /* Process will be terminated by thread function */ } SEE ALSO mq_close(3), mq_getattr(3), mq_open(3), mq_receive(3), mq_send(3), mq_unlink(3), mq_overview(7) Linux 2.6.16 2006-02-25 MQ_NOTIFY(3)