poisx消息队列是通过消息的优先级来实现双方的发送和接受,与之相似的System V消息队列是用整型来标记每一条消息。
posix_mqsend.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <stdlib.h>
#include <string.h>
int main()
{
mqd_t mqdes;
char buf[]="hello";
mqdes = mq_open("/mymqs",O_RDWR | O_CREAT, 0664,NULL);
if(mqdes == (mqd_t)-1)
{
printf("mq_open error\n");
exit(1);
}
mq_send(mqdes,buf,strlen(buf)+1,1); //优先级为1
mq_close(mqdes); //关闭posix消息队列
return 0;
}
posix_mqrecv.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <stdlib.h>
#include <string.h>
int main()
{
mqd_t mqdes = -1;
char *buf;
struct mq_attr *attr;
mqdes = mq_open("/mymqs",O_RDWR | O_CREAT, 0664,NULL);
if(mqdes == (mqd_t)-1)
{
printf("mq open error\n");
exit(1);
}
mq_getattr(mqdes,attr); //获取消息队列属性
buf = (char*)malloc(attr->mq_msgsize);
if(mq_receive(mqdes,buf,attr->mq_msgsize,0) < 0) //0为不使用优先级来接受消息,默认会从高优先级接受
{
printf("mq_receive error\n");
exit(1);
}
printf("buf=%s\n",buf);
mq_close(mqdes); //关闭posix消息队列
return 0;
}
gcc编译的时候,使用 -l 参数加上 rt 库
posix_mqsend.c : gcc posix_mqsend.c -o posix_mqsend -lrt
posix_mqrecv.c : gcc posix_mqrecv.c -o posix_mqsend -lrt
查看是否创建消息队列成功和消息队列中已有的消息字节数 :
- cd /dev/mqueue
- cat mymqs