本文给出了一个demo,说明Linux应用编程中mq_open/mq_send/mq_receive几个API的基本使用方法。
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <stdio.h>
#include <unistd.h>
#define TEST_MQ_FILE_NAME "/test_mq"
#define TEST_MESSAGE_SIZE 100
int main(int argc, char **argv)
{
mqd_t mqd;
struct mq_attr attr= {
.mq_flags = 0,
.mq_maxmsg = 1,
.mq_msgsize = TEST_MESSAGE_SIZE,
.mq_curmsgs = 0
};
char msg[TEST_MESSAGE_SIZE];
int count;
int ret;
if((argc != 2) || (argv[1][0] != '0' && argv[1][0] != '1')) {
printf("usage: %s 0|1\n", argv[0]);
return -1;
}
mqd = mq_open(TEST_MQ_FILE_NAME, O_RDWR | O_CREAT, 0777, &attr);
if(mqd < 0) {
perror("mq_open");
return -1;
}
if(argv[1][0] == '0') {
/* send */
while(1) {
sprintf(msg, "test msg %d", count++);
ret = mq_send(mqd, msg, sizeof(msg), 0);
if(ret < 0) {
perror("mq_send");
continue;
}
sleep(1);
}
} else {
/* receive */
while(1) {
ret = mq_receive(mqd, msg, sizeof(msg), NULL);
if(ret < 0) {
perror("mq_receive");
}
printf("received msg: %s\n", msg);
}
}
return 0;
}
程序中创建了一个消息队列,并通过参数选择本进程是send还是receive。
消息队列被创建后,可以通过mount命令查看它的状态:
mkdir /tmp/mq
mount -t mqueue none /tmp/mq/
cat /tmp/mq/test_mq