POSIX Message Queue

In the previous chapter we learned about System V message queue. In this chapter we shall learn about POSIX message queue

You should include below header to use Message Queue:

#include <mqueue.h>

Below are the API for using Message Queue:

1. mq_open()

mqd_t mq_open( const char *name, int oflag, … )

It will open a message queue with the “name” and returns a message-queue descriptor.

2. mq_close()

int mq_close( mqd_t mqdes );

It will close the association between the message queue descriptor and a message queue.

3. mq_send()

int mq_send( mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned int msg_prio );

It is used to send a message pointed by “msg_ptr” with the length “msg_len” into the message queue.

You can also assign the priority by filling “msg_prio”.

4. mq_receive()

int mq_receive( mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned int *msg_prio );

It is sued to receive a message from message queue,

5. mq_setattr()

int mq_setattr( mqd_t mqdes, const struct mq_attr *mqstat, struct mq_attr *omqstat );

It is used to set mq_flags of the structure mqstat.

6. mq_getattr()
int mq_getattr( mqd_t mqdes, struct mq_attr *mqstat );

It is used to get the attributes of the queue referenced by the message queue descriptor mqdes.

7. mq_notify()

int mq_notify( mqd_t mqdes, const struct sigevent *notification );

It will notify the calling process when the queue becomes non empty.

8. mq_unlink()
int mq_unlink( const char *name );

It is sued to delete a message queue

Example of message queue

#include <stdio.h>
#include <stdlib.h>
#include <mqueue.h>


#define MAX_MSG_SIZE 4096
#define MAX_MSGS     2

int main( void )
{
	//create and send a message queue
	mqd_t mqdSend = mq_open ("/OpenCSF_MQ", O_CREAT | O_EXCL | O_WRONLY, 0600, NULL);
 	mq_send (mqdSend, "HELLO", 6, 10);
	mq_close (mqdSend);

	//open a message queue for reading
	mqd_t mqd = mq_open ("/OpenCSF_MQ", O_RDONLY);
	struct mq_attr attr;
	char *buffer = calloc (attr.mq_msgsize, 1);

	//retrieve the message from message queue
	int priority = 0;
	if ((mq_receive (mqd, buffer, attr.mq_msgsize, &priority)) == -1)
	  printf ("Failed to receive message\n");
	else
	  printf ("Received [priority %u]: '%s'\n", priority, buffer);

	//cleanup
	free (buffer);
	buffer = NULL;
	mq_close (mqd);
}

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *