note
1.mq_open函数的参数pathname应以/开始,且最多一个/
2.mq_receive的参数msg_len应大于等于attr.msgsize
3.消息队列写方写时不要求读方就绪,读方读时不要求写方就绪(和管道不同)
code
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/wait.h>
// mq_open\mq_close\mq_unlink\mq_getattr\mq_setattr\mq_send\mq_receive\mq_notify
const char* msq_queue_instance = "/posix_msg_queue";
mqd_t msg_queue_id = 0;
long msglen = 0;
void parent_work(void) {
int i = 0;
time_t t = 0;
int ret = -1;
char* sendBuf = (char*)malloc(msglen);
for (i = 0; i < 10; i++) {
memset(sendBuf, 0, msglen);
time(&t);
sprintf(sendBuf, "i am parent process,%s", ctime(&t));
ret = mq_send(msg_queue_id, sendBuf, strlen(sendBuf), 0);
if (ret == -1) {
fprintf(stderr, "parent process mq_send error,%s\n", strerror(errno));
}
else if (ret == 0) {
fprintf(stdout, "parent process mq_send success\n");
}
sleep(1);
}
wait(NULL);
free(sendBuf);
(void)mq_unlink(msq_queue_instance);
exit(EXIT_SUCCESS);
}
void child_work(void) {
int i = 0;
int ret1 = -1;
ssize_t ret2 = -1;
struct mq_attr attr;
char* rcvBuf = (char*)malloc(msglen);
for (i = 0; i < 10; ++i) {
//fprintf(stdout, "child process in loop\n");
ret1 = mq_getattr(msg_queue_id, &attr);
if (ret1 == 0) {
fprintf(stdout, "flag:%ld,maxmsg:%ld,msgsize:%ld,curmsgs:%ld\n", attr.mq_flags, attr.mq_maxmsg, attr.mq_msgsize, attr.mq_curmsgs);
memset(rcvBuf, 0, msglen);
ret2 = mq_receive(msg_queue_id, rcvBuf, msglen, 0);
if (ret2 >= 0) {
fprintf(stdout, "child process recieve msg:%s\n", rcvBuf);
}
else if (ret2 == -1) {
fprintf(stderr, "child process mq_receive error,%s\n", strerror(errno));
}
}
else if (ret1 == -1) {
fprintf(stderr, "child process mq_getattr error,%s\n", strerror(errno));
}
sleep(1);
}
free(rcvBuf);
exit(EXIT_SUCCESS);
}
int main(int argc, char** argv) {
int ret = -1;
struct mq_attr attr;
pid_t pid = 0;
msg_queue_id = mq_open(msq_queue_instance, O_CREAT|O_RDWR, 666, NULL); // 默认属性
if (msg_queue_id == -1) {
fprintf(stderr, "parent process mq_open error,%s\n", strerror(errno));
exit(EXIT_FAILURE);
}
// 设置消息队列属性
attr.mq_flags = 0;
attr.mq_maxmsg = 100;
attr.mq_msgsize = 1024;
attr.mq_curmsgs = 0;
ret = mq_setattr(msg_queue_id, &attr, NULL);
if (ret == -1) {
fprintf(stderr, "parent process mq_setattr error,%s\n", strerror(errno));
(void)mq_unlink(msq_queue_instance);
exit(EXIT_FAILURE);
}
ret = mq_getattr(msg_queue_id, &attr);
if (ret == -1) {
fprintf(stderr, "parent process mq_getattr error,%s\n", strerror(errno));
(void)mq_unlink(msq_queue_instance);
exit(EXIT_FAILURE);
}
msglen = attr.mq_msgsize;
pid = fork();
if (pid < 0) {
fprintf(stderr, "parent process fork error,%s\n", strerror(errno));
(void)mq_unlink(msq_queue_instance);
exit(EXIT_FAILURE);
}
if (pid > 0) {
fprintf(stdout, "parent process:%d\n", getpid());
parent_work();
}
else if (pid == 0) {
fprintf(stdout, "child process:%d\n", getpid());
child_work();
}
return 0;
}
test