读取消息队列代码
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
//int msgget(key_t key, int msgflg);
//ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
// int msgflg);
struct msgbuf{
long mtype; /* message type, must be > 0 */
char mtext[128]; /* message data */
};
int main()
{
// 创建消息队列结构体
struct msgbuf readBuf;
// 获取消息队列
int msgId = msgget(0x1234, IPC_CREAT|0777);
if(msgId == -1){
perror("why");
}
// 接收消息队列里面的数据,由于只获取消息队列里面的mtext数据,只接收该大小
msgrcv(msgId, &readBuf, sizeof(readBuf.mtext), 888, 0);
printf("recv from que: %s\n", readBuf.mtext);
//int msgctl(int msqid, int cmd, struct msqid_ds *buf);
// 控制消息队列,最后删除该消息队列,防止内存造成过多队列存在。
msgctl(msgId, IPC_RMID, 0); // argument 3 is because of none thing to do.
return 0;
}
消息队列 写 代码
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
//int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
struct msgbuf{
long mtype; /* message type, must be > 0 */
char mtext[128]; /* message data */
};
int main()
{
struct msgbuf writeBuf = {888, "this is from que!"};
int msgId = msgget(0x1234, IPC_CREAT|0777);
if(msgId == -1){
perror("why");
}
int ret = msgsnd(msgId, &writeBuf, strlen(writeBuf.mtext), 0);
// msgctl(msgId, IPC_RMID, 0); // argument 3 is because of none thing to do.
return 0;
}
msgbuf结构体里面的mtype是为了在获取消息队列里面的内容时按类型获取,如想获取888队列里面的内容,读写两端都需要在888里面进行操作。例如广播平台 一样,不同频道发送不同的内容,观众要调到对应的频道才能获取到对应的内容。
对于查看Linux系统里面创建了多少队列,共享内存等信息,可以使用以下链接里面的东西。
ipc /-m /-q /-s
https://blog.csdn.net/Nick_666/article/details/78288813?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2allfirst_rank_v2~rank_v25-3-78288813.nonecase&utm_term=linux%E6%9F%A5%E7%9C%8B%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97%E4%B8%AD%E6%B6%88%E6%81%AF%E6%95%B0%E9%87%8F
本文介绍了如何在C语言中使用消息队列,包括读取和写入消息队列的代码示例。通过mtype字段可以按消息类型进行筛选,类似广播平台的频道选择。同时,提供了查看Linux系统中消息队列、共享内存等信息的方法。
779

被折叠的 条评论
为什么被折叠?



