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

     

  • 相关阅读:
    mac 清除 iTerm2 终端屏幕内容
    Spring学习笔记4 Bean的作用域
    Qt::WindowFlags
    A48基于NRF24L01的无线心率血氧体温检测
    作为图形渲染API,OpenGL和Direct3D的全方位对比。
    【Java】运算符
    【slam十四讲第二版】【课本例题代码向】【第十一讲~回环检测】【DBoW3的安装】【创建字典】【相似度检测】【增加字典规模】
    Windows与网络基础:子网掩码和子网划分
    从0开始学习JavaScript--JavaScript中的集合类
    如何在Rocky Linux和AlmaLinux上安装MySQL 8.0
  • 原文地址:https://blog.csdn.net/qq_63626307/article/details/126515683