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

消息队列属于IPC
两个进程间要通过消息队列进行通信,比如A通过消息队列给B传送一个消息。首先A要建立一个消息队列,然后A往该消息队列里面发送消息(由一个有特殊形式的结构体构成,包括数据类型和数据内容),当不需要使用这个消息队列的时候删除消息队列。B要做的事情是打开消息队列,打开方式是用和A里面一样的键值打开对应的消息队列,然后接收消息队列的消息(即结构体中某个类型的数据),结束。

相关函数

创建/打开消息队列  msgget

发送数据  msgsnd

从消息队列取消息  msgrcv

删除消息队列   msgctl


例如A进程代码

#include

#include

#include

#include

#include

#include


struct msgt

{

    long msgtype;

    char msgtext[1024];

};


void main()

{

    int msqid;

    int msg_type;

    char str[256];

    struct msgt 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

{

    long msgtype;

    char msgtext[1024];

};


void myprocess()

{

    struct msgt ms;

    int x;

    

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

    

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

}


void main()

{

    int i;

    int cpid;

    

    //打开消息队列

    msqid = msgget(1025, IPC_EXCL);

    

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

    

    myprocess();

}



 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章