这个是参照网络上面的例子写的,不过还是调用linux接口来实现的,基本没有难度。
之所以还是记录下来,还是希望对消息队列机制有更加深一点的理解吧
其实我的初衷还是想要自己实现一个类似于消息队列这样的机制,以便于在没有操作系统下也能运用。
消息队列接收函数:
#include<unistd.h>
#include<stdio.h>#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define MAX_VALUE 128
struct msgbuf{
long mtype;
char mtext[MAX_VALUE];
};
void main()
{
int msgid=-1;
struct msgbuf data;
long int msg_type=0;
//创建一个消息队列
msgid= msgget((key_t)1234,0666|IPC_CREAT);
if(msgid==-1){
printf("****创建消息队列失败!****\n");
exit(EXIT_FAILURE);
}
while(1){
if(msgrcv(msgid,(void*)&data,MAX_VALUE,msg_type,0)==-1){
printf("****接收消息失败****!\n");
exit(EXIT_FAILURE);
}
printf("recved:%s\n",data.mtext);
if(strcmp(data.mtext,"end")==0)
{
printf("****谈话结束****\n");
break;
}
}
if(msgctl(msgid,IPC_RMID,0)==-1){
printf("****删除队列失败****\n");
exit(EXIT_FAILURE);
}
exit(EXIT_FAILURE);
}
消息队列发送函数:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define MAX_VALUE 128
struct msgbuf{
long mtype;
char mtext[MAX_VALUE];
};
void main(){
int msgid=-1;
char mtext[128];
long int msg_type=1;
struct msgbuf data;
msgid=msgget((key_t)1234,0666|IPC_CREAT);
if(-1==msgid){
printf("****创建消息队列失败****\n");
exit(EXIT_FAILURE);
}
while(1){
printf(">:输入你想要发送的信息\n");
scanf("%s",mtext);
strcpy(data.mtext,mtext);
if(msgsnd(msgid,(void*)&data,MAX_VALUE,msg_type)==-1){
printf("****发送信息失败****\n");
exit(EXIT_FAILURE);
}
if(strcmp(mtext,"end")==0){
printf("*****谈话结束*****\n");
break;
}
}
exit(EXIT_SUCCESS);
}