• 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;

     

  • 相关阅读:
    红外遥控视力自动检测系统的设计与实现
    前端知识点个人实践
    2024年研究生网上报名各类问题类似参考解答系列之—社保类疑问
    电容笔可以用什么代替?好用电容笔品牌推荐
    微信小程序开发学习—Day1
    String 常用方法
    java计算机毕业设计ssm+vue个人时间规划系统
    单元测试 :Junit框架
    『C++ - STL』之优先级队列( priority_queue )
    淘宝/天猫获取卖出的商品订单列表 API 返回值说明
  • 原文地址:https://blog.csdn.net/qq_63626307/article/details/126515683