消息队列(Message Queue)是一种进程间通信(IPC)机制,允许不同的进程通过发送和接收消息来进行通信。在Linux系统中,消息队列通常通过系统调用如msgget
、msgsnd
、msgrcv
和msgctl
来实现。
以下是一个简单的System V消息队列的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[100]; /* message data */
};
int main() {
key_t key;
int msgid;
struct msgbuf msg;
key = ftok("/tmp/example", 65);
msgid = msgget(key, 0666 | IPC_CREAT);
msg.mtype = 1;
strcpy(msg.mtext, "Hello, World!");
msgsnd(msgid, &msg, sizeof(msg.mtext), 0);
printf("Message sent: %s\n", msg.mtext);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[100]; /* message data */
};
int main() {
key_t key;
int msgid;
struct msgbuf msg;
key = ftok("/tmp/example", 65);
msgid = msgget(key, 0666 | IPC_CREAT);
msgrcv(msgid, &msg, sizeof(msg.mtext), 1, 0);
printf("Received message: %s\n", msg.mtext);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
通过以上方法和示例代码,可以有效利用Linux的消息队列机制进行进程间通信。
领取专属 10元无门槛券
手把手带您无忧上云