消息队列应用实例
2014-05-26 17:08
288 查看
在于都apue的消息队列部分时,发现书中并没有相关的实例,这里自己写了一个简单的小例子,加深对消息队列的理解,子进程从终端读取消息传入消息队列,转载请尊重原创、保留相关链接本文来自多宝平台:http://www.mbodb.com
父进程,读取消息队列中的消息,并打印到终端。
点击(此处)折叠或打开
#include "apue.h"
#include <sys/msg.h>
#include <sys/ipc.h>
struct mymesg{ //定义消息结构
long mtype; //消息类型
char mtext[512]; //消息实际数据
};
int
main(void)
{
struct mymesg mesg;
int pid;
int mesgno;
mesg.mtype=1;
int running=1;
ssize_t m;
key_t key;
if((key=ftok("megqueue.c",'a'))==-1)//使用ftok生成创建消息队列要使用的key,注意第一个参数必须是一个现存文件的路径
printf("ftok error\n");
if((mesgno=msgget(key,IPC_CREAT|S_IRUSR|S_IWUSR))==-1)//创建消息队列
printf("creat message queue error\n");
printf("messgae no:%d\n",mesgno);//输出消息队列标示符
if((pid=fork())<0)
printf("fork error\n");
else if(pid==0) //子进程从终端读取消息传入消息队列
{
while(running)
{
if(fgets(mesg.mtext,512,stdin)!=NULL)
{printf("%s\n",mesg.mtext); msgsnd(mesgno,&mesg,521,0);}
else
{
printf("getmsg error\n");
break;
}
}
}
else //父进程,读取消息队列中的消息,并打印到终端
{
while((m=msgrcv(mesgno,&mesg,512,0,MSG_NOERROR))!=-1)
printf("parent:%s\n",mesg.mtext);
printf("over\n");
}
exit(0);
}
运行结果:
![](http://blog.chinaunix.net/attachment/201304/12/28541347_1365772664s8Gz.jpg)
注意CTRL+C结束进程后,多宝消息队列并没有删除
父进程,读取消息队列中的消息,并打印到终端。
点击(此处)折叠或打开
#include "apue.h"
#include <sys/msg.h>
#include <sys/ipc.h>
struct mymesg{ //定义消息结构
long mtype; //消息类型
char mtext[512]; //消息实际数据
};
int
main(void)
{
struct mymesg mesg;
int pid;
int mesgno;
mesg.mtype=1;
int running=1;
ssize_t m;
key_t key;
if((key=ftok("megqueue.c",'a'))==-1)//使用ftok生成创建消息队列要使用的key,注意第一个参数必须是一个现存文件的路径
printf("ftok error\n");
if((mesgno=msgget(key,IPC_CREAT|S_IRUSR|S_IWUSR))==-1)//创建消息队列
printf("creat message queue error\n");
printf("messgae no:%d\n",mesgno);//输出消息队列标示符
if((pid=fork())<0)
printf("fork error\n");
else if(pid==0) //子进程从终端读取消息传入消息队列
{
while(running)
{
if(fgets(mesg.mtext,512,stdin)!=NULL)
{printf("%s\n",mesg.mtext); msgsnd(mesgno,&mesg,521,0);}
else
{
printf("getmsg error\n");
break;
}
}
}
else //父进程,读取消息队列中的消息,并打印到终端
{
while((m=msgrcv(mesgno,&mesg,512,0,MSG_NOERROR))!=-1)
printf("parent:%s\n",mesg.mtext);
printf("over\n");
}
exit(0);
}
运行结果:
![](http://blog.chinaunix.net/attachment/201304/12/28541347_1365772664s8Gz.jpg)
注意CTRL+C结束进程后,多宝消息队列并没有删除