Linux: Message Queues

Message Queue is a linked list of message structures stored inside the kernel’s memory space and accessible by multiple processes. 

New messages are added at the end of the queue. 


Messages may be obtained from the queue either in a FIFO manner (default) or by requesting a specific type of message (based on message type).

Each message has a message type associated with it. A Message Queue reader can specify which type of message that it will read. Or it can say that it will read all messages in order.

It is quite possible to have any number of Msg Queue readers, or writers. In fact the same process can be both a writer and a reader.


  • Each message structure must start with a long message type:
      struct mymsg 
      {
           long msg_type;
           char mytext[512]; /* rest of message */
           int somethingelse;
      };

Each message queue is limited in terms of both the maximum number of messages it can contain and the maximum number of bytes it may contain.
 

New messages cannot be added if either limit is hit (new writes will normally block).

On linux, these limits are defined as (in /usr/include/linux/msg.h):
        –MSGMAX 8192 /*total number of messages */
        –MSBMNB 16384 /* max bytes in a queue */

Creating a Message Queue:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

            int msgget (key_t key, int msgflg);


The key parameter is either a non-zero identifier for the queue to be created or the value IPC_PRIVATE, which guarantees that a new queue is created. 

The msgflg parameter is the read-write permissions for the queue OR’d with one of two flags: 

IPC_CREAT will create a new queue or return an existing one.

IPC_EXCL added will force the creation of a new queue, or return an error.

Writing to a Message Queue:

           int msgsnd (int msqid, const void * msg_ptr, size_t msg_size, int msgflags);

   msgqid is the id returned from the msgget call
   msg_ptr is a pointer to the message structure 
   msg_size is the size of that structure 
   msgflags defines what happens when no message of the appropriate type is waiting, and can be set to the following: 
          IPC_NOWAIT (non-blocking, return –1 immediately if queue is empty)

Reading from a Message Queue:

      int msgrcv(int msqid, const void * msg_ptr, size_t msg_size, long msgtype, int msgflags);

   msgqid is the id returned from the msgget call
   msg_ptr is a pointer to the message structure
   msg_size is the size of that structure
   msgtype is set to: = 0 first message available in FIFO stack
                             > 0 first message on queue whose type equals type 
   msgflags defines what happens when no message of the appropriate type is waiting, and can be set to the following: 

        IPC_NOWAIT (non-blocking, return –1 immediately if queue is empty)

Message Queue Control:

    int msgctl(int msqid, int cmd, struct msqid_ds * buf);

No comments:

Post a Comment