【C语言】消息队列

本文介绍了如何在C语言中使用消息队列,包括读取和写入消息队列的代码示例。通过mtype字段可以按消息类型进行筛选,类似广播平台的频道选择。同时,提供了查看Linux系统中消息队列、共享内存等信息的方法。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

读取消息队列代码

#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

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值