linux下的消息队列数据收发
在 Linux 下,可以使用 POSIX 消息队列来实现一个线程向另一个线程发送消息。以下是一个完整的 C 程序示例,展示了如何创建两个线程,一个线程发送消息,另一个线程接收消息:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <mqueue.h>
#include <fcntl.h>
#include <sys/stat.h>#define QUEUE_NAME "/my_message_queue"
#define MAX_MSG_SIZE 1024
#define MSG_COUNT 5// 消息队列描述符
mqd_t mqdes;// 接收线程函数
void *receive_thread(void *arg) {char buffer[MAX_MSG_SIZE];ssize_t bytes_received;// 循环接收消息for (int i = 0; i < MSG_COUNT; i++) {bytes_received = mq_receive(mqdes, buffer, MAX_MSG_SIZE, NULL);if (bytes_received == -1) {perror("mq_receive");exit(EXIT_FAILURE);}buffer[bytes_received] = '\0';printf("Received message: %s\n", buffer);}// 关闭消息队列if (mq_close(mqdes) == -1) {perror("mq_close");exit(EXIT_FAILURE);}// 删除消息队列if (mq_unlink(QUEUE_NAME) == -1) {perror("mq_unlink");exit(EXIT_FAILURE);}return NULL;
}// 发送线程函数
void *send_thread(void *arg) {char message[MAX_MSG_SIZE];// 循环发送消息for (int i = 0; i < MSG_COUNT; i++) {snprintf(message, MAX_MSG_SIZE, "Message %d", i + 1);if (mq_send(mqdes, message, strlen(message), 0) == -1) {perror("mq_send");exit(EXIT_FAILURE);}printf("Sent message: %s\n", message);}return NULL;
}int main() {pthread_t sender, receiver;struct mq_attr attr;// 设置消息队列属性attr.mq_flags = 0;attr.mq_maxmsg = 10;attr.mq_msgsize = MAX_MSG_SIZE;attr.mq_curmsgs = 0;// 创建消息队列mqdes = mq_open(QUEUE_NAME, O_CREAT | O_RDWR, 0666, &attr);if (mqdes == (mqd_t)-1) {perror("mq_open");return EXIT_FAILURE;}// 创建发送线程if (pthread_create(&sender, NULL, send_thread, NULL) != 0) {perror("pthread_create (sender)");return EXIT_FAILURE;}// 创建接收线程if (pthread_create(&receiver, NULL, receive_thread, NULL) != 0) {perror("pthread_create (receiver)");return EXIT_FAILURE;}// 等待发送线程结束if (pthread_join(sender, NULL) != 0) {perror("pthread_join (sender)");return EXIT_FAILURE;}// 等待接收线程结束if (pthread_join(receiver, NULL) != 0) {perror("pthread_join (receiver)");return EXIT_FAILURE;}return EXIT_SUCCESS;
}
代码说明:
消息队列的创建和初始化:
mq_open
函数用于创建一个新的消息队列或打开一个已存在的消息队列。struct mq_attr
结构体用于设置消息队列的属性,如最大消息数和消息大小。
发送线程:
send_thread
函数循环发送 5 条消息到消息队列中。mq_send
函数用于将消息发送到消息队列。
接收线程:
receive_thread
函数循环从消息队列中接收 5 条消息。mq_receive
函数用于从消息队列中接收消息。- 接收完所有消息后,关闭并删除消息队列。
主线程:
- 创建发送线程和接收线程。
- 使用
pthread_join
函数等待两个线程结束。
编译和运行:
将上述代码保存为 message_queue_example.c
,然后使用以下命令进行编译:
gcc -o message_queue_example message_queue_example.c -lpthread -lrt
运行编译后的可执行文件:
./message_queue_example
运行程序后,你将看到发送和接收的消息输出。