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

linux消息列队

2015-11-23 10:04 579 查看
消息列队跟管道差不多,但是和管道不同的是,消息列表不用开关。它能够独立于发送和接收进程而存在,这消除在同步命名管道的打开和关闭可能产生的一些困难。

主要用到函数有下面几个:

int msgctl(int msgid , ing cmd , struct msgid_ds *buf);

int msgget(key_t key , ingt msgflg);

int msgrcv(ing msgid , void* msg_ptr , size_t msg_sz , long int msgtype , int msgflg);

int msgsnd(int msgid , const void* msg_ptr , size_t msg_sz , int msgflg);

这些函数的作用跟共享内存和信号量的作用是相同的。

int msgctl(int msgid , ing cmd , struct msgid_ds *buf);: 控制函数,用来控制消息列队的关闭等。

int msgget(key_t key , ingt msgflg);用来创建一个消息列队

int msgrcv(ing msgid , void* msg_ptr , size_t msg_sz , long int msgtype , int msgflg);用来接收一个消息

int msgsnd(int msgid , const void* msg_ptr , size_t msg_sz , int msgflg);用来发送一个消息

下面来看一个具体的例子。在这个例子中,我们将在客户端中对消息进行接收,在接收完所有的消息后,删除消息列队。

在服务器中,我们将发送消息到消息列队中,直到遇到end结束符为止。

下面来看具体的例子:

#include <iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/msg.h>
using namespace std;

//msg1 用来接收消息。接收者在接收完最后一个消息后删除它

struct my_msg_st{
long int my_msg_type;
char some_text[BUFSIZ];
};

int main()
{
//cout << "Hello World!" << endl;

int running = 1;
int msgid;
struct my_msg_st some_data;
long int msg_to_receive = 0;

//首先是创建消息列队
msgid = msgget((key_t)1234 , 0666 | IPC_CREAT);
if( msgid == -1){
fprintf(stderr , "msgget failed with error: %d\n" , errno);
exit(EXIT_FAILURE);
}

//从消息列队获取消息,直到遇见end消息为止,最后删除消息列队

while(running){
if(msgrcv(msgid , (void*)&some_data , BUFSIZ , msg_to_receive , 0) == -1){
//接受消息失败
fprintf(stderr , "msgrcv failed with error: %d\n" , errno);
exit(EXIT_FAILURE);
}
printf("You Wrote: %s" , some_data.some_text);
if(strncmp(some_data.some_text , "end" , 3) == 0 ){
running = 0;
}
}

if(msgctl(msgid , IPC_RMID , 0 ) == -1){
fprintf(stderr , "msgctl(IPC_RMID) failed!\n");
exit(EXIT_FAILURE);
}

exit(EXIT_SUCCESS);

//return 0;
}


#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>

#include<sys/msg.h>

#define MAX_TEXT 32

struct my_msg_st{
long int my_msg_type;
char some_text[MAX_TEXT];
};

int main(){
int running = 1;
struct my_msg_st some_data;
int msgid;

char buffer[BUFSIZ];

msgid = msgget((key_t)1234 , 0666|IPC_CREAT);
if(msgid == -1){
fprintf(stderr , "msgget failied with error: %d\n" , errno);
exit(EXIT_FAILURE);
}

while(running){
//从标准输入中获取消息
printf("Enter some text: ");
fgets(buffer , BUFSIZ , stdin);
some_data.my_msg_type = 1;
strcpy(some_data.some_text , buffer);

//发送消息
if(msgsnd(msgid , (void*)&some_data , MAX_TEXT , 0 ) == -1){
fprintf(stderr , "msgsnd failed!\n");
exit(EXIT_FAILURE);
}

if(strncmp(buffer , "end" , 3) == 0)
{
running = 0;
}

}

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