追根问题的挖掘消息队列源码

一,特点

(1)解析1

  1. 消息队列是IPC对象的一种
  2. 消息队列由消息队列ID来唯一标识
  3. 消息队列就是一个消息的列表。用户可以在消息队列中添加消息、读取消息等。
  4. 消息队列可以按照类型来发送(添加)/接收(读取)消息

(2)解析2

消息队列,是消息的链接表,存放在内核中,一个消息队列由一个标识符(即队列ID)来标识。

特点:

1、消息队列是面向记录的,其中的消息具有特定的格式一级特定的优先级

2、消息队列独立于发送与接受进程。进程终止时,消息队列及其内容并不会被删除

3、消息队列可以实现消息的随机查询,消息不一定要以先进先出的次序读取,也可以按消息的类型读取

二,源码详解

1,接受端

#include "msg_queue_peer.h"

struct msgbuf
{
    long mtype;
    char mdata[256];
};

int main(int argc, char *argv[])
{
    struct msgbuf recv_buf;

    while (1)
    {
        if(msg_queue_recv("topic", &recv_buf, sizeof(recv_buf), 0, 0) > 0)
        {
            printf("recv from msga type = %ld\n", recv_buf.mtype);
            printf("recv from msga data = %s\n", recv_buf.mdata);
        }
        else
        {
            perror("recv error:");
            return -1;
        }
    }


    pause();

    return 0;
}

2,发送端

#include "msg_queue_peer.h"

struct msgbuf
{
    long mtype;
    char mdata[256];
};

int main(int argc, char *argv[])
{
    struct msgbuf send_buf;

    //这个mtype可以不用,但是必须赋一个不小于0的数
    send_buf.mtype = 1;

    while (1)
    {
        gets(send_buf.mdata, 256);

        if(msg_queue_send("topic", &send_buf, sizeof(send_buf), 0) < 0)
        {
            printf("msg_queue_send error\n");
            return -1;
        }
    }


    pause();

    return 0;
}

3,创建消息队列

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
 
int msgget(key_t key, int msgflg);
 
key_t key: 创建新的消息队列
int msgflg: 赋予新消息队列的权限,IPC_CREAT|0777
 
成功返回队列ID,失败返回-1

4,发送消息队列

 #include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
 
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
成功返回0,失败返回-1
 
int msqid:            消息队列标识符
const void *msgp:     msgp是一个任何类型的结构体,是消息队列的地址
size_t msgsz:         要发送消息的大小,不含消息类型占用的4个字节,即mtext的长度
int msgflg:           默认写0,当消息队列满时,msgsnd将会阻塞,直到消息能写进消息队列 
 
 
const void *msgp的结构体如下:
struct msgbuf{
 
    long mtype;        //message type,must be>0
    char mtext[128];    //message data
}
 

5,读取消息队列

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
 
      
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
成功返回消息数据的长度,失败返回-1
 
int msqid         :消息队列标识符
void *msgp        :存放消息队列的结构体,结构体类型要与msgsnd函数发送的类型相同
size_t msgsz      : 要接受消息的大小,不含消息类型占用的4个字节
long msgtyp       :要读消息的类型,如写:888
int msgflg        :默认写0:阻塞式接收消息,没有该类型的消息msgrcv函数一直阻塞等待

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值