您的位置:首页 > 运维架构 > Linux

linux进程通信:消息队列

2016-04-26 21:23 681 查看
消息队列可以实现两个没有关系的进程之间的通信。

创建了一个消息队列后,进程可以往里面放消息,也可以取消息。因为这个消息队列是有名字的,所以就算是两个没有关系的进程,也能通信。

而且人性化的一点是,可以自己定义消息的结构体。

几个重要的函数:

//创建消息队列,如果存在就直接获取
int msgget(key_t, key, int msgflg);
//第一个参数是key整形,用于区分不同的队列
//返回key命名的队列id,唯一标识一个队列

//发送消息
int msgsend(int msgid, const void *msg_ptr, size_t msg_sz, int msgflg);
//msgid是标识队列的id
//msg_ptr是自己定义的消息结构体,注意结构体里面是长整型开始

//所以要定义成这样
struct my_message{
long int message_type;
/* The data you wish to transfer*/
};

//获取消息
int msgrcv(int msgid, void *msg_ptr, size_t msg_st, long int msgtype, int msgflg);
//参数跟上面一样


效果图:





Server的代码:(用于取消息)

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/msg.h>

struct msg_st
{
long int msg_type;
char text[256];
};

int main(){

int msgid = -1;

struct msg_st data;

long int msgtype = 0;

msgid = msgget((key_t)1234,IPC_CREAT);

if(msgid == -1){

printf("msgget failed\n");

exit(EXIT_FAILURE);

}

printf("Server start!\n");

while(1){

if(msgrcv(msgid, (void*)&data, 256, msgtype, 0) == -1){
printf("msgrcv failed\n");
exit(EXIT_FAILURE);
}//end if

//success
printf("from client:%s\n",data.text);

}//end while

}


Client.c的代码:(用于发消息)

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/msg.h>

struct msg_st

{

long int msg_type;

char text[256];

};

int main(){

struct msg_st data;
int msgid = -1;
char buffer[256];

memset(buffer,'\0',256);

msgid = msgget((key_t)1234,IPC_CREAT);

if(msgid == -1){
printf("msgget failed\n");
exit(EXIT_FAILURE);
}

while(1){

printf("Enter a string\n");
fgets(buffer,256,stdin);
strcpy(data.text,buffer);
data.msg_type=1;

msgsnd(msgid, (void*)&data,256, 0);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: