linux进程间通信-------消息队列

来源:互联网 发布:淘宝运营每天做什么 编辑:程序博客网 时间:2024/06/04 01:05
消息队列属于IPC
两个进程间要通过消息队列进行通信,比如A通过消息队列给B传送一个消息。首先A要建立一个消息队列,然后A往该消息队列里面发送消息(由一个有特殊形式的结构体构成,包括数据类型和数据内容),当不需要使用这个消息队列的时候删除消息队列。B要做的事情是打开消息队列,打开方式是用和A里面一样的键值打开对应的消息队列,然后接收消息队列的消息(即结构体中某个类型的数据),结束。

相关函数

创建/打开消息队列 msgget

发送数据 msgsnd

从消息队列取消息 msgrcv

删除消息队列  msgctl


例如A进程代码

#include

#include

#include

#include

#include

#include


struct msgt

{

    longmsgtype;

    charmsgtext[1024];

};


void main()

{

    intmsqid;

    intmsg_type;

    charstr[256];

    structmsgt msgs;

   

   //创建消息队列

    msqid =msgget(1025, IPC_CREAT);

   

    //循环

   while(1)

    {

   printf("please input message type, 0 for quit!\n");

   //获取消息类型

   scanf("%d", &msg_type);

   

   //如果用户输入的消息为0,则退出

   if(msg_type == 0)

   break;

   

   printf("please input message data!\n");

   //获取消息数据

   scanf("%s", str);

   

   msgs.msgtype = msg_type;

   strcpy(msgs.msgtext, str);

   

   //发送消息

   msgsnd(msqid, &msgs, sizeof(struct msgt), 0);

    }

   

   //删除消息队列

   msgctl(msqid, IPC_RMID, 0);

 

}



B进程代码

#include

#include

#include

#include

#include

#include


int msqid;


struct msgt

{

    longmsgtype;

    charmsgtext[1024];

};


void myprocess()

{

    structmsgt ms;

    intx;

   

    x =msgrcv(msqid, &ms, sizeof(struct msgt), 0, 0);

   

   printf("the receive text: %s   %d\n", ms.msgtext, x);

}


void main()

{

    inti;

    intcpid;

   

   //打开消息队列

    msqid =msgget(1025, IPC_EXCL);

   

   printf("the msqid is %d\n", msqid);

   

   myprocess();

}



 

 

 

 

原创粉丝点击