Linux进程消息队列
一、基础概念
消息队列是Linux进程间通信(IPC)的一种方式,它允许一个或多个进程向另一个或多个进程发送消息。这些消息按照发送的顺序被接收,并且每个消息都有一个特定的类型标识,接收进程可以根据类型选择性地接收消息。
二、优势
三、类型
Linux中的消息队列主要分为两种类型:
四、应用场景
五、常见问题及解决方法
六、示例代码(使用POSIX消息队列)
以下是一个简单的POSIX消息队列示例代码,包括发送方和接收方两个进程:
// 发送方代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#define QUEUE_NAME "/test_queue"
#define MSG_CONTENT "Hello, World!"
#define MSG_PRIORITY 1
int main() {
mqd_t mq;
struct mq_attr attr;
char buffer[100];
// 设置队列属性
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = 100;
attr.mq_curmsgs = 0;
// 创建队列
mq = mq_open(QUEUE_NAME, O_CREAT | O_RDWR, 0644, &attr);
if (mq == -1) {
perror("mq_open");
exit(1);
}
// 发送消息
if (mq_send(mq, MSG_CONTENT, strlen(MSG_CONTENT) + 1, MSG_PRIORITY) == -1) {
perror("mq_send");
mq_close(mq);
exit(1);
}
printf("Message sent: %s
", MSG_CONTENT);
// 关闭队列
mq_close(mq);
return 0;
}
// 接收方代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#define QUEUE_NAME "/test_queue"
int main() {
mqd_t mq;
char buffer[100];
// 打开队列
mq = mq_open(QUEUE_NAME, O_RDONLY);
if (mq == -1) {
perror("mq_open");
exit(1);
}
// 接收消息
if (mq_receive(mq, buffer, 100, NULL) == -1)
领取专属 10元无门槛券
手把手带您无忧上云