• IO进线程:消息队列


    消息队列可以使用类型来发送和接收消息

    key: IPC_PRIVATE, ftok

    创建或打开消息队列:msgget

    添加消息(发送消息): msgsnd

    读取消息(接收消息): msgrcv

    控制消息(删除消息队列): msgctl

    ------------------------------------------------------------------------------

    信息队列的创建与添加信息:

    #include
    #include
    #include
    #include
    #include
    #include
    #include

    struct msgbuf{
        long mtype;   //消息类型
        char mtext[100]; //消息正文
    };

    int main(int argc, char *argv[])

        key_t key = ftok(".", 'b');
        if (key < 0)
        {
            perror("ftok");
            return -1;
        }

        int msgid = msgget(key, IPC_CREAT|0777);
        if (msgid < 0)
        {
            perror("msgget");
            return -1;
        }

        //添加消息
        struct msgbuf buf = {1};
        while (1)
        {
            printf("Input type: ");
            scanf("%ld", &buf.mtype);
            getchar();
            printf("Send: ");
            fgets(buf.mtext, sizeof(buf.mtext), stdin);
            if (0 > msgsnd(msgid, &buf, sizeof(buf)-sizeof(long), 0))
            {
                perror("msgsnd");
                break;
            }
            if (strncmp(buf.mtext, "quit", 4) == 0)
                break;
        }

        return 0;


    ---------------------------------------------------------------------------

    信息队列的读取与删除信息队列:

    #include
    #include
    #include
    #include
    #include
    #include ipc.h>
    #include

    struct msgbuf{
        long mtype;   //消息类型
        char mtext[100]; //消息正文
    };

    int main(int argc, char *argv[])

        key_t key = ftok(".", 'b');
        if (key < 0)
        {
            perror("ftok");
            return -1;
        }

        int msgid = msgget(key, 0777);
        if (msgid < 0)
        {
            perror("msgget");
            return -1;
        }

        //读取消息
        struct msgbuf buf;
        while (1)
        {
            if (0 > msgrcv(msgid, &buf, sizeof(buf)-sizeof(long), 1, 0))
            {
                perror("msgrcv");
                break;
            }
            printf("recv: %s\n", buf.mtext);
            if (strncmp(buf.mtext, "quit", 4) == 0)
                break;
        }
        sleep(1);
        if (0 > msgctl(msgid, IPC_RMID, NULL))
        {
            perror("msgctl");
            return -1;
        }

        return 0;

     

  • 相关阅读:
    Google Earth Engine-06(GEE操作方法)
    鸿蒙HarmonyOS实战-ArkUI组件(Progress)
    金仓数据库KingbaseES接口协议解析工具使用指南(2. 概述)
    干洗店上门洗护小程序开发,互联网洗鞋店软件
    2022杭电多校九 1008-Shortest Path in GCD Graph(质因子+容斥)
    效率提升75%!要做矩阵号,更要做好矩阵号管理
    Java中的代码重构:技巧、优秀实践与方法
    webpack5从零开始,到打包一个项目的基本配置
    【源码课件+教程】Python入门教程_Python400集持续更新
    基于SpringBoot的植物健康系统
  • 原文地址:https://blog.csdn.net/qq_63626307/article/details/126515683