Posix message queue is way to communicate data between process.
This could use for producer-consumer kind of algorithm.
whenever use this code in daemon, use syslog and strerror(errno) function instead of perror.
Compiling and linking
Header file
#include <mqueue.h> library -lrt use for linking
open a message queue with name.
bool open_queue(mqd_t& mqid,const string& queue_name,unsigned int maxqueue,unsigned int msgsize)
{
// First we need to set up the attribute structure
struct mq_attr attr;
attr.mq_maxmsg =maxqueue;
attr.mq_msgsize = msgsize;
attr.mq_flags = 0;
// Open a queue with the attribute structure
mqid = mq_open (queue_name.c_str(), O_RDWR | O_CREAT | O_NONBLOCK, 0666, &attr);
if(mqid==(mqd_t)-1){
perror("Error:mq_open: "); // use syslog and strerror(errno) for daemon
return false;
}
return true;
}
closing a message
inline void close_queue(mqd_t& mqid)
{
mq_close(mqid);
}
Send or write message to queue
void send_message(mqd_t& mqid, const std::string& str_msg,unsigned int priority)
{
if (mq_send (mqid, str_msg.c_str(), str_msg.length(), priority) == -1)
perror ("Error:mq_send: ");
// use syslog and strerror(errno) for daemon
}
Get count of message available in queue.
int get_message_count(mqd_t& mqid)
{
int ret=0
struct mq_attr attr;
if(mq_getattr (mqid, &attr)==0){
ret= attr.mq_curmsgs;
}
else
perror("Error:mq_getattr: ");
return ret;
}
Get the max size of messages.
int get_message_size(mqd_t& mqid)
{
int ret=0;
struct mq_attr attr;
if(mq_getattr (mqid, &attr)==0){
ret= attr.mq_msgsize;
}
else
perror("Error:mq_getattr: ");
return ret;
}
Get a message from message queue.
bool get_message(mqd_t& mqid,const std::string& str_msg)
{
bool ret=false;
int msgsize = get_message_size(mqid);
if(msgsize && get_message_count(mqid)){
char* buf= new buf[msgsize+1];
memset(buf,0,msgsize+1);
if(mq_receive (mqid, buf, msgsize, &prio) != -1){
str_msg=std::string(buf);
ret=true;
}
delete[] buf;
}
return ret;
}
No comments:
Post a Comment
would you like it. :)