在Linux系统中,消息队列(Message Queue,简称MQ)是一种进程间通信(IPC)机制,允许进程之间发送和接收消息。常见的Linux消息队列实现有POSIX消息队列和System V消息队列。
POSIX消息队列是基于POSIX标准的消息队列,使用mq_open
、mq_send
、mq_receive
等函数进行操作。
POSIX消息队列不需要单独的启动命令,它是在应用程序中通过编程接口进行操作的。以下是一个简单的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mqueue.h>
#define QUEUE_NAME "/my_queue"
#define MAX_MSG_SIZE 100
#define MSG_PRIORITY 1
int main() {
mqd_t mq;
struct mq_attr attr;
char buffer[MAX_MSG_SIZE + 1];
// 设置队列属性
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = MAX_MSG_SIZE;
attr.mq_curmsgs = 0;
// 创建队列
mq = mq_open(QUEUE_NAME, O_CREAT | O_RDWR, 0644, &attr);
if (mq == (mqd_t)-1) {
perror("mq_open");
exit(1);
}
// 发送消息
if (mq_send(mq, "Hello, World!", strlen("Hello, World!"), MSG_PRIORITY) == -1) {
perror("mq_send");
mq_close(mq);
mq_unlink(QUEUE_NAME);
exit(1);
}
// 接收消息
if (mq_receive(mq, buffer, MAX_MSG_SIZE, NULL) == -1) {
perror("mq_receive");
mq_close(mq);
mq_unlink(QUEUE_NAME);
exit(1);
}
buffer[MAX_MSG_SIZE] = '\0';
printf("Received message: %s
", buffer);
// 关闭并删除队列
mq_close(mq);
mq_unlink(QUEUE_NAME);
return 0;
}
System V消息队列是早期UNIX系统中的消息队列实现,使用msgget
、msgsnd
、msgrcv
等函数进行操作。
System V消息队列也不需要单独的启动命令,它是在应用程序中通过编程接口进行操作的。以下是一个简单的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MSG_KEY 1234
#define MSG_TYPE 1
struct msgbuf {
long mtype;
char mtext[100];
};
int main() {
int msgid;
struct msgbuf sbuf, rbuf;
// 创建消息队列
msgid = msgget(MSG_KEY, 0644 | IPC_CREAT);
if (msgid == -1) {
perror("msgget");
exit(1);
}
// 发送消息
sbuf.mtype = MSG_TYPE;
strcpy(sbuf.mtext, "Hello, World!");
if (msgsnd(msgid, &sbuf, sizeof(sbuf.mtext), 0) == -1) {
perror("msgsnd");
msgctl(msgid, IPC_RMID, NULL);
exit(1);
}
// 接收消息
if (msgrcv(msgid, &rbuf, sizeof(rbuf.mtext), MSG_TYPE, 0) == -1) {
perror("msgrcv");
msgctl(msgid, IPC_RMID, NULL);
exit(1);
}
printf("Received message: %s
", rbuf.mtext);
// 删除消息队列
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
mq_open
、mq_send
、mq_receive
等函数进行操作。msgget
、msgsnd
、msgrcv
等函数进行操作。这两种消息队列都不需要单独的启动命令,而是在应用程序中通过编程接口进行操作。选择哪种消息队列取决于具体的应用需求和系统支持情况。
领取专属 10元无门槛券
手把手带您无忧上云