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

     

  • 相关阅读:
    使用Http请求实现数据的批量导入
    相关程序漏洞导致的容器逃逸
    excel表格转pdf格式的方法介绍
    C++核心编程类的总结封装案例
    电脑msvcp140丢失报错解决方法,msvcp140.dll重新安装的解决方法
    用DIV+CSS技术设计的餐饮美食网页与实现制作(web前端网页制作课作业)HTML+CSS+JavaScript美食汇响应式美食菜谱网站模板
    通过SSH 可以访问Ubuntu Desktop吗?
    Spire.PDF for .NET【文档操作】演示:设置 PDF 文档的 XMP 元数据
    Linux:基础详细版1:文件管理常用命令
    Select、Poll、Epoll的优缺点
  • 原文地址:https://blog.csdn.net/qq_63626307/article/details/126515683