Linux MQ接收与发送
参数说明:
// 消息队列的标志。目前,这个字段只用于设置或获取O_NONBLOCK标志,以指示消息队列是否应该以非阻塞模式打开
attr.mq_flags = 0;
// 队列中允许的最大消息数
attr.mq_maxmsg = 10;
// 每条消息的最大字节数
attr.mq_msgsize = MSG_SIZE;
// 当前在队列中的消息数(注意:这个字段在mq_open调用时应该被设置为0,因为它是只读属性,用于获取当前队列中的消息数量,而不是设置它)
attr.mq_curmsgs = 0;
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mqueue.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#define MAX_SIZE 1024
// 发送线程函数
void* sender_thread(void* arg) {
char msg_buf[] = "Hello, POSIX message queue!";
struct mq_attr attr;
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = MAX_SIZE;
attr.mq_curmsgs = 0;
// 创建消息队列
mqd_t mq = mq_open("/queue_a", O_CREAT | O_RDWR, 0644, &attr);
if (mq == (mqd_t)-1) {
perror("a mq open");
exit(1);
}
while (1) {
if (mq_send(mq, msg_buf, strlen(msg_buf) + 1, 0) == -1) {
perror("mq_send");
}
// printf("Message sent: %s\n", msg_buf);
sleep(1); // 等待接收线程处理或模拟发送间隔
}
// 清理资源(在实际应用中,应该在适当的时机关闭消息队列和线程)
mq_close(mq);
mq_unlink("/queue_a");
return NULL;
}
// 接收线程函数
void* receiver_thread(void* arg) {
struct mq_attr attr;
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = MAX_SIZE;
attr.mq_curmsgs = 0;
char buffer[MAX_SIZE];
ssize_t bytes_read;
// 创建消息队列
mqd_t mq = mq_open("/queue_b", O_CREAT | O_RDWR, 0644, &attr);
if (mq == (mqd_t)-1) {
perror("b mq open");
exit(1);
}
while (1) {
bytes_read = mq_receive(mq, buffer, MAX_SIZE, NULL);
if (bytes_read != -1) {
printf("Message received: %s\n", buffer);
}
usleep(100);
}
// 清理资源(在实际应用中,应该在适当的时机关闭消息队列和线程)
mq_close(mq);
mq_unlink("/queue_b");
return NULL;
}
int main() {
pthread_t sender_tid, receiver_tid;
if (pthread_create(&sender_tid, NULL, sender_thread, NULL) != 0) {
perror("pthread_create sender");
exit(1);
}
if (pthread_create(&receiver_tid, NULL, receiver_thread, NULL) != 0) {
perror("pthread_create receiver");
exit(1);
}
pthread_join(sender_tid, NULL);
pthread_join(receiver_tid, NULL);
return 0;
}
编译命令
gcc -o e e.c -lrt -lpthread