消息队列实例
/*********************程序相关信 息*********************
程序编号:012
程序编写起始日期:2008.11.1
程序编写完成日期:2008.11.1
程序修改日 期: 修改备注:
程序目的:学习linux 消息队列通信
所用主要函 数:msgget(),msgsnd(),msgrcv(),msgctl()
程序 存疑:
程序完成地点: 宿舍内
*********************程序相关信息*********************/
#include
#include
#include
#include
#include
#include
int main()
{
int pid,msqid;//后者为消息队列识别代号
struct msgbuf
{
long mtype;//消息类型
char mtext[20];//消息内容
}send_buf,receive_buf;
if((msqid=msgget(IPC_PRIVATE,0700))
{
printf("msgget建立消息队列失败。\n");
exit(1);
}
else
printf("msgget建立消息队列成功,该消息队列识别代号为%d。\n",msqid);
if((pid=fork())
{
printf("fork()函数调用失败!\n");
exit(2);
}
else if(pid>0)//父进程,发送消息到消息队列
{
send_buf.mtype=1;
strcpy(send_buf.mtext,"My test information");
printf("发送到消息队列的信息内容为:%s\n",send_buf.mtext);
if(msgsnd(msqid,&send_buf,20,IPC_NOWAIT)
{
printf("msgsnd消息发送失败。\n");
exit(3);
}
else
printf("msgsnd消息发送成功。\n");
sleep(2);
exit(0);
}
else//子进程,从消息队列中接收消息]
{
sleep(2);//等待父进程发送消息完成
int infolen;//读到的信息数据长度
if((infolen=msgrcv(msqid,&receive_buf,20,0,IPC_NOWAIT))
printf("msgrcv读取信息错误。\n");
exit(4);
}
else
printf("msgrcv读取信息成功。\n");
printf("自消息队列读取到的内容为%s,共读取%d个字节。\n",receive_buf.mtext,infolen); if((msgctl(msqid,IPC_RMID,NULL))
{
printf("msgctl函数调用出现错误。\n");
exit(5);
}
else
{
printf("识别代号为%d的消息队列已经被成功删除。\n",msqid);
exit(0);
}
}
}