用c语言写一个消息队列
时间: 2024-04-29 09:26:50 浏览: 12
好的,下面是一个简单的消息队列实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#define MSG_SIZE 1024
#define MSG_TYPE 1
struct msgbuf {
long mtype;
char mtext[MSG_SIZE];
};
int main() {
key_t key;
int msgid;
struct msgbuf msg;
// 生成key值
if ((key = ftok(".", 'a')) == -1) {
perror("ftok error");
exit(1);
}
// 创建消息队列
if ((msgid = msgget(key, IPC_CREAT|0666)) == -1) {
perror("msgget error");
exit(1);
}
// 发送消息
strcpy(msg.mtext, "Hello, message queue!");
msg.mtype = MSG_TYPE;
if (msgsnd(msgid, &msg, strlen(msg.mtext)+1, 0) == -1) {
perror("msgsnd error");
exit(1);
}
// 接收消息
if (msgrcv(msgid, &msg, MSG_SIZE, MSG_TYPE, 0) == -1) {
perror("msgrcv error");
exit(1);
}
printf("Received message: %s\n", msg.mtext);
// 删除消息队列
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl error");
exit(1);
}
return 0;
}
```
该程序首先使用 `ftok` 函数生成一个key值,然后使用 `msgget` 函数创建一个消息队列。接着,向消息队列中发送一条消息,使用 `msgsnd` 函数实现。接着,使用 `msgrcv` 函数接收消息队列中的消息。最后,使用 `msgctl` 函数删除消息队列。