标签:
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 != ‘\0‘ && 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] = ‘\0‘;
/*
* 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);
}
标签:
原文地址:http://www.cnblogs.com/qingxueyunfeng/p/4711167.html