zoukankan      html  css  js  c++  java
  • Linux进程间通信之消息队列

      马上过年了,心里万般滋味。。。

      

    一,消息队列

    1,概念:“消息队列”是在消息的传输过程中保存消息的容器

    2,消息队列就是一个消息的链表。可以把消息看作一个记录,具有特定的格式以及特定的优先级。

      对消息队列有写权限的进程可以向消息队列中按照一定的规则添加新消息

      对消息队列有读权限的进程则可以从消息队列中读走消息

      消息队列是随内核持续的。

    3,编程注意事项:使用时先把数据封装成消息,把消息存入队列

    编程步骤: 具体函数的用法可以用man手册查看(强力推荐)

    (1)ftok()生产key

    (2)使用msgget( ) 创建/获取消息队列,返回值是队列标识符

    (3)使用msgsnd( ) 发送消息

        使用msgrcv( ) 接收消息

    (4)使用msgctl( ) 删除消息队列

    4,实例:

    sendmsg.c   用来发送消息的

    // sendmsg.c
    
    #include<stdio.h>
    #include<stdlib.h>
    #include<unistd.h>
    #include<sys/types.h>
    #include<sys/ipc.h>
    #include<sys/msg.h>
    #include<string.h>
    
    struct my_msg
    {
        int mtype; // 消息类型
        char buf[256];
    }msg1, msg2;
    
    int main()
    {
        key_t key = ftok("./", 88);
    
        int msgid = msgget(key, 0666|IPC_CREAT);
        if(-1 == msgid)
        {
            perror("msgget failed!!!");
            exit(1);
        }
    
        msg1.mtype = 2;
        strcpy(msg1.buf, "hello, msg2");
        msgsnd(msgid, &msg1, sizeof(msg1), 0); // 阻塞
    //    msgsnd(msgid, &msg1, sizeof(msg1), IPC_NOWAIT); // 非阻塞
    
        msg2.mtype = 1;
        strcpy(msg2.buf, "hello, msg1");
        msgsnd(msgid, &msg2, sizeof(msg2), 0); // 阻塞
    
        printf("消息发送完成,按回车销毁消息队列
    ");
        getchar();
    
        if(-1 == shmctl(msgid, IPC_RMID, NULL))
        {
            perror("shmctl failed");
            exit(2);
        }
        return 0;
    }

    recvmsg.c  用来接收消息的

    // recvmsg.c
    
    #include<stdio.h>
    #include<stdlib.h>
    #include<unistd.h>
    #include<sys/types.h>
    #include<sys/ipc.h>
    #include<sys/msg.h>
    #include<string.h>
    
    struct my_msg
    {
        int mtype; // 消息类型
        char buf[256];
    }msg;
    
    int main()
    {
        key_t key = ftok("./", 88);
    
        // 获取消息队列
        int msgid = msgget(key, 0);
        if(-1 == msgid)
        {
            perror("msgget failed!!!");
            exit(1);
        }
    
        int res = msgrcv(msgid, &msg, sizeof(msg),
                2, // 取消息类型为2的消息
                0);
        printf("类型:%d, 内容:%s
    ", msg.mtype, msg.buf);
    
        printf("消息接收完成,按回车销毁消息队列
    ");
        getchar();
    
        if(-1 == shmctl(msgid, IPC_RMID, NULL))
        {
            perror("shmctl failed");
            exit(2);
        }
        return 0;
    }

    5,运行结果

     

    6,获取代码  

    git clone https://github.com/xcywt/xcyipc.git

    有人看到这个麻烦再乌班图中试试这个库有没有建好。主要是学习github的一些用法。

  • 相关阅读:
    javascript 中数字计算精度缺失问题
    javascript闭包
    MySQL数据库的创建
    原生项目使用 sass
    git工具命令
    如何将你的node服务放到线上服务器
    Cookie、Session、Token 的区别
    东北师大-构建之法-2020秋最终成绩(并非期末成绩)
    20201220-东北师范大学-助教-周总结-第14次
    东北师范大学-构建之法-20201207作业成绩
  • 原文地址:https://www.cnblogs.com/xcywt/p/5172885.html
Copyright © 2011-2022 走看看