zoukankan      html  css  js  c++  java
  • posix消息队列(1)

    1.消息队列也可以认为是消息链表,《unix网络编程卷二》中用下图表示了消息队列的可能分布。

    2.关于消息队列的函数如下所示:

    #include <mqueue.h>
    //创建,打开或删除IPC的函数
    mqd_t mq_open(const char *name,int flag,/*mode_t mode,struct mq_attr *attr */);
    int mq_close(const char *name);
    int mq_unlink(const char *name);
    //控制IPC操作的函数
    int mq_getattr(mqd_t mqdes,struct mq_attr *attr);
    int mq_setattr(mqd_t mqdes,const struct mq_attr *attr,struct mq_attr *oattr);
    //ipc操作函数
    int mq_send(mqd_t mqdes,const char *ptr,size_t len,unsigned int prio);
    int mq_receive(mqd_t mqdes,char *ptr,size_t len, unsigned int *priop);
    int mq_notify(mqd_t mqdes,const struct sigevent *notification);

    3.例子

    环境为ubuntu+eclipse

    出现的的问题:

    a, undefined reference to `mq_open'

       …………………………………………………………

    解决方法:

           可以在工程属性里面加上链接rt库

          具体:如图所示

    #include <stdio.h>
    #include <stdlib.h>
    #include<mqueue.h>
    #define    FILE_MODE    (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
    int main(void) {
        int flag;
        mode_t mode=FILE_MODE;
        mqd_t mq;
        int prio;
        struct mq_attr attr;
        char name[]="/test";
        char msg[]="I'm a test";
        int receive_size;
        char *ptr;
        flag=O_RDWR|O_CREAT;
        mq=mq_open(name,flag,mode,NULL);
        //查看消息队列的属性
        mq_getattr(mq,&attr);
        printf("max #msgs=%ld,max #bytes/msg=%ld,#currently on queue=%ld
    ",attr.mq_maxmsg,
                attr.mq_msgsize,attr.mq_curmsgs);
        //发送消息
        printf("发送的消息为:msg=%s
    ",msg);
        mq_send(mq,msg,sizeof(msg)+1,120);
        //发送消息后,查看消息队列的属性
        mq_getattr(mq,&attr);
        printf("max #msgs=%ld,max #bytes/msg=%ld,#currently on queue=%ld
    ",attr.mq_maxmsg,
                   attr.mq_msgsize,attr.mq_curmsgs);
         //接受消息
        ptr=(char *)malloc(sizeof(char)*attr.mq_msgsize);
        receive_size=mq_receive(mq,ptr,attr.mq_msgsize,&prio);
        printf("接收的消息为:receive_size =%d,ptr=%s,prio=%d
    ",receive_size,ptr,prio);
        //接收消息后,查看消息队列的属性
        mq_getattr(mq,&attr);
        printf("max #msgs=%ld,max #bytes/msg=%ld,#currently on queue=%ld
    ",attr.mq_maxmsg,
                   attr.mq_msgsize,attr.mq_curmsgs);
        mq_unlink(name);
        return EXIT_SUCCESS;
    }

     运行结果为:

    max #msgs=10,max #bytes/msg=8192,#currently on queue=0
    发送的消息为:msg=I'm a test
    max #msgs=10,max #bytes/msg=8192,#currently on queue=1
    接收的消息为:receive_size =12,ptr=I'm a test,prio=120
    max #msgs=10,max #bytes/msg=8192,#currently on queue=0
  • 相关阅读:
    jenkins集群(三) -- master和slave配置git
    jenkins集群(二)(master --> slave) -- allure自动化测试报告部署
    jenkins集群(一) -- 在Linux上部署
    APP自动化 -- contexts(上下文切换)
    APP自动化 -- 滑动解锁、滑动验证
    APP自动化 -- 坐标获取和点击
    APP自动化 -- 获取toast元素的文本内容
    APP自动化 -- MobileBy
    Python学习-基础数据类型补充操作、bytes类型
    Kafka-生产者、消费者、自定义分区器
  • 原文地址:https://www.cnblogs.com/sklww/p/3490857.html
Copyright © 2011-2022 走看看