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

 
原文地址:https://www.cnblogs.com/lcw/p/3159517.html