zoukankan      html  css  js  c++  java
  • 【消息】linux之消息队列

     
    1.机制

       消息队列的运行方式与命名管道非常相似。

    欲与其他进程通信的进程只需要将消息发送到消息队列中,目的进程就从消息队列中读取需要的消息。


    2.源码

    1)发送方

    //msg_send.c
    #include <sys/types.h>
    #include <sys/msg.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
    int main()
    {
        int msg_id,msg_flags;
        int reval;
        char send_msg[64];
        msg_flags=IPC_CREAT|0666;
        msg_id=msgget((key_t)456,msg_flags);
        if(-1==msg_id)
        {
            printf("msg create error.
    ");
            exit(EXIT_FAILURE);
        }
        memset(send_msg,0,64);
        sprintf(send_msg,"Hi,I'm %d.",getpid());
        reval=msgsnd(msg_id,send_msg,sizeof(send_msg),0);
        if(-1==reval)
        {
            printf("message send error.
    ");
            exit(EXIT_FAILURE);
        }
        else
            printf("Send message:%s
    ",send_msg);
        return 0;
    }
    View Code
    2)接收方
    //msg_rcvr.c
    #include <sys/types.h>
    #include <sys/msg.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
    int main()
    {
        int msg_id,msg_flags;
        int reval;
        char send_msg[64];
        msg_flags=IPC_CREAT|0666;
        msg_id=msgget((key_t)456,msg_flags);
        if(-1==msg_id)
        {
            printf("msg create error.
    ");
            exit(EXIT_FAILURE);
        }
        memset(send_msg,0,64);
        reval=msgrcv(msg_id,send_msg,64,0,0);
        if(-1==reval)
        {
            printf("message send error.
    ");
            exit(EXIT_FAILURE);
        }
        else
            printf("Received msg:%s
    ",send_msg);
                                       
        reval=msgctl(msg_id,IPC_RMID,0);
        if(-1==reval)
        {
            printf("remove msg queue error
    ");
            exit(EXIT_FAILURE);
        }
        return 0;
    }
    View Code

    3.mystery注解

       1)msgget()函数与信号量的semget()函数相似,作用是创建一个消息队列。
       2)msqid为消息队列ID
       3)消息队列可以在几个进程之间复用,具有一定的独立性,比命名管道更加灵活,也不需要打开与关闭。

       4)在最后一个进程使用完消息队列后,不要忘记删除这个消息队列

     
  • 相关阅读:
    原型设计作业
    20210405-1 案例分析作业
    要命的作业
    20210309-1 准备工作
    20210309-2 阅读任务
    前端用js获取本地文件的内容
    2019春第四周作业
    解决BootStap TreeView插件在 BootStrap4上不兼容问题
    ABP VNEXT使用PUT方法时报”对象已被修改,乐观并发失败“解决方案
    【一步一步入坑ABP VNEXT】安装ABP CLI
  • 原文地址:https://www.cnblogs.com/lcw/p/3159517.html
Copyright © 2011-2022 走看看