msgrcv 是一个用于在 Linux 系统中接收消息队列消息的系统调用
#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include<stdio.h>#include <stdlib.h>#include<string.h>定义消息结构体:struct msgbuf { long mtype; // 消息类型 char mtext[256]; // 消息内容};创建并获取消息队列ID:key_t key = ftok("/tmp/msgfile", 65); // 使用ftok函数生成键值if (key < 0) { perror("ftok"); exit(1);}int msgid = msgget(key, 0666 | IPC_CREAT); // 使用msgget函数获取消息队列IDif (msgid < 0) { perror("msgget"); exit(2);}使用 msgrcv 接收消息:struct msgbuf rcvbuffer;long msgtype = 1; // 指定要接收的消息类型,这里接收类型为1的消息ssize_t size = msgrcv(msgid, &rcvbuffer, sizeof(rcvbuffer.mtext), msgtype, 0);if (size < 0) { perror("msgrcv"); exit(3);}处理接收到的消息:printf("Received message: type = %ld, text = %s\n", rcvbuffer.mtype, rcvbuffer.mtext);删除消息队列(可选):if (msgctl(msgid, IPC_RMID, NULL) < 0) { perror("msgctl"); exit(4);}完整示例代码:#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include<stdio.h>#include <stdlib.h>#include<string.h>struct msgbuf { long mtype; char mtext[256];};int main() { key_t key = ftok("/tmp/msgfile", 65); if (key < 0) { perror("ftok"); exit(1); } int msgid = msgget(key, 0666 | IPC_CREAT); if (msgid < 0) { perror("msgget"); exit(2); } struct msgbuf rcvbuffer; long msgtype = 1; ssize_t size = msgrcv(msgid, &rcvbuffer, sizeof(rcvbuffer.mtext), msgtype, 0); if (size < 0) { perror("msgrcv"); exit(3); } printf("Received message: type = %ld, text = %s\n", rcvbuffer.mtype, rcvbuffer.mtext); if (msgctl(msgid, IPC_RMID, NULL) < 0) { perror("msgctl"); exit(4); } return 0;}编译并运行上述代码,即可在 Linux 环境下正确使用 msgrcv 接收消息。注意,你需要先运行发送消息的程序,然后再运行接收消息的程序,以便在消息队列中有消息可供接收。


