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)在最后一个进程使用完消息队列后,不要忘记删除这个消息队列

     
  • 相关阅读:
    HTML5开发手机项目—个人总结
    将win7电脑无线网变身WiFi热点,让手机、笔记本共享上网
    Docker Compose 入门使用指南
    使用Phoenix通过sql语句更新操作hbase数据
    分布式版本管理git学习资料整理推荐
    博客迁移至新平台ixirong.com
    浅谈PipelineDB系列一: Stream数据是如何写到Continuous View中的
    Postgres是如何管理空值的
    如何简单愉快的上手PipelineDB
    nanomsg 如何写数据到PipelineDB
  • 原文地址:https://www.cnblogs.com/lcw/p/3159517.html
Copyright © 2011-2022 走看看