Client:
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <mqueue.h>
#include <unistd.h>
#include <stdio.h>
#define Msg_server "/msgqueue"
#define Buf_len 20000
int main (int argc,char** argv)
{
mqd_t QD;
int Len;
ssize_t Rec_len;
Char Rec_buf[buf_len];
char *p = NULL;
memset (rec_buf, 1, sizeof (REC_BUF));
/*
* OPN Message Queue
*/
if (qd = Mq_open (msg_server, o_rdonly, 0, NULL)) < 0)
{
printf ("Open msg queue error.\n");
Exit (-1);
}
/*
* Read msg
*/
while (1)
{
if (Rec_len = mq_receive (QD, rec_buf, sizeof (REC_BUF), 0)) < 0)
{
printf ("Receive msg error.\n");
Exit (-1);
}
Else
{
printf ("Receive msg successfully.\n");
for (p = rec_buf; *p! = ' + ' && p! = (rec_buf + rec_len); ++p)
{
printf ("%c", *p);
}
}
Sleep (2);
}
Mq_close (QD);
Mq_unlink (Msg_server);
Exit (0);
}
Server:
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <mqueue.h>
#include <stdio.h>
#include <unistd.h>
#define Msg_server "/msgqueue"
#define Buf_len 100
int main (int argc, char** argv)
{
mqd_t QD;
struct mq_attr *attr;
mode_t access;
Char Send_buf[buf_len];
Access = S_IRUSR | S_IWUSR | S_iroth;
if (attr = (struct mq_attr *) malloc (sizeof (struct mq_attr)) = = NULL)
{
printf ("Alloc memory error!\n");
Exit (-1);
}
memset (attr, 0, sizeof (struct mq_attr));
memset (send_buf, 1, sizeof (SEND_BUF));
Send_buf[buf_len-1] = ' + ';
/*
* Create Message Queue
*/
if (qd = Mq_open (msg_server, O_RDWR | O_creat | O_EXCL, Access, NULL)) < 0)
{
printf ("Open msg queue error.\n");
Exit (-1);
}
/*
* Get Default attr
*/
printf ("Get Message Queue default attr:\n");
if (mq_getattr (QD, attr) < 0)
{
printf ("Get attr error.\n");
}
else if (attr! = NULL)
{
printf ("Default msg count:%ld, msgsize:%ld \ n", attr->mq_maxmsg, attr->mq_msgsize);
}
Free (attr);
/*
* Send msg
*/
while (1)
{
if (Mq_send (QD, send_buf, sizeof (SEND_BUF), 0) < 0)
{
printf ("Send msg error.\n");
Exit (-1);
}
Else
{
printf ("Send msg successfully.\n");
}
Sleep (2);
}
Mq_close (QD);
Mq_unlink (Msg_server);
Exit (0);
}
Linux Message Queue Demo