1.消息队列也可以认为是消息链表,《unix网络编程卷二》中用下图表示了消息队列的可能分布。
2.关于消息队列的函数如下所示:
#include <mqueue.h> //创建,打开或删除IPC的函数 mqd_t mq_open(const char *name,int flag,/*mode_t mode,struct mq_attr *attr */); int mq_close(const char *name); int mq_unlink(const char *name); //控制IPC操作的函数 int mq_getattr(mqd_t mqdes,struct mq_attr *attr); int mq_setattr(mqd_t mqdes,const struct mq_attr *attr,struct mq_attr *oattr); //ipc操作函数 int mq_send(mqd_t mqdes,const char *ptr,size_t len,unsigned int prio); int mq_receive(mqd_t mqdes,char *ptr,size_t len, unsigned int *priop); int mq_notify(mqd_t mqdes,const struct sigevent *notification);
3.例子
环境为ubuntu+eclipse
出现的的问题:
a, undefined reference to `mq_open'
…………………………………………………………
解决方法:
可以在工程属性里面加上链接rt库
具体:如图所示
#include <stdio.h> #include <stdlib.h> #include<mqueue.h> #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) int main(void) { int flag; mode_t mode=FILE_MODE; mqd_t mq; int prio; struct mq_attr attr; char name[]="/test"; char msg[]="I'm a test"; int receive_size; char *ptr; flag=O_RDWR|O_CREAT; mq=mq_open(name,flag,mode,NULL); //查看消息队列的属性 mq_getattr(mq,&attr); printf("max #msgs=%ld,max #bytes/msg=%ld,#currently on queue=%ld ",attr.mq_maxmsg, attr.mq_msgsize,attr.mq_curmsgs); //发送消息 printf("发送的消息为:msg=%s ",msg); mq_send(mq,msg,sizeof(msg)+1,120); //发送消息后,查看消息队列的属性 mq_getattr(mq,&attr); printf("max #msgs=%ld,max #bytes/msg=%ld,#currently on queue=%ld ",attr.mq_maxmsg, attr.mq_msgsize,attr.mq_curmsgs); //接受消息 ptr=(char *)malloc(sizeof(char)*attr.mq_msgsize); receive_size=mq_receive(mq,ptr,attr.mq_msgsize,&prio); printf("接收的消息为:receive_size =%d,ptr=%s,prio=%d ",receive_size,ptr,prio); //接收消息后,查看消息队列的属性 mq_getattr(mq,&attr); printf("max #msgs=%ld,max #bytes/msg=%ld,#currently on queue=%ld ",attr.mq_maxmsg, attr.mq_msgsize,attr.mq_curmsgs); mq_unlink(name); return EXIT_SUCCESS; }
运行结果为:
max #msgs=10,max #bytes/msg=8192,#currently on queue=0 发送的消息为:msg=I'm a test max #msgs=10,max #bytes/msg=8192,#currently on queue=1 接收的消息为:receive_size =12,ptr=I'm a test,prio=120 max #msgs=10,max #bytes/msg=8192,#currently on queue=0