消息队列通信实验报告_实验报告7modbus通信
消息队列通信实验报告由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“实验报告7modbus通信”。
实验6 消息队列通信
实验目的1、了解什么是消息、消息队列
2、掌握消息传送的机理
实验内容
1、消息的创建、发送和接收。使用系统调用msgget(),msgsnd(),msgrev(),及msgctl()编制一长度为1k的消息发送和接收的程序。
Msgqid.c #include
#include
#include
#include
#define MSGKEY 75
/*定义关键词MEGKEY*/
struct msgform
/*消息结构*/
{
long mtype;
char mtext[1030];/*文本长度*/
}msg;
int msgqid,i;
void CLIENT()
{
int i;
msgqid=msgget(MSGKEY,0777);
for(i=10;i>=1;i--)
{
msg.mtype=i;
printf(“(client)sentn”);
msgsnd(msgqid,&msg,1024,0);/*发送消息msg入msgid消息队列*/
}
exit(0);
}
void SERVER()
{
msgqid=msgget(MSGKEY,0777|IPC_CREAT);/*由关键字获得消息队列*/
do
{
msgrcv(msgqid,&msg,1030,0,0);/*从msgqid队列接收消息msg */
printf(“(server)receivedn”);
}while(msg.mtype!=1);
/*消息类型为1时,释放队列*/
msgctl(msgqid,IPC_RMID,0);
exit(0);
}
main()
{
while((i=fork())==-1);
if(!i)SERVER();
while((i=fork())==-1);
if(!i)CLIENT();
wait(0);
wait(0);
}
实验结果:
2、选做实验:模拟从c/s通信
客户端client功能:
1)显示服务功能菜单
Enter your choice: 1.2.Save noney Take money 2)接收用户键入的功能号进行选择;3)将用户键入的功能号作为一条消息发送到消息队列,然后结束 服务端功能:
1)从消息队列接收client发送的一条消息; 2)根据消息作如下处理: 若消息为“1”,创建子进程1,子进程1加载服务模块save,该模块显示以下信息:Your money was saved!若消息为“2”,创建子进程2,子进程2加载服务模块take,该模块显示以下信息:
Please take your money!3)等待子进程终止后,server消息对列结束。
注意:1)save和take要事先编译连接好,放在同一目录下;
2)先运行客户端进程,再运行服务端进程。
1、client.c #include #include #include #include #include #define MSGKEY 75 struct msgform
{ long mtype;
char mtext[1000];}msg;int msgqid;
void client(){
int i;msgqid=msgget(MSGKEY,0777);
/*打开75#消息队列*/ for(i=20;i>=1;i--){ msg.mtype=i;printf(“(client)sent %dn”,i);sleep(3);msgsnd(msgqid,&msg,1024,0);
/*发送消息*/ } exit(0);} main(){
client();} server.c #include #include #include #include #include #define MSGKEY 75 struct msgform
{ long mtype;
char mtext[1000];}msg;int msgqid;
void server(){
msgqid=msgget(MSGKEY,0777|IPC_CREAT);/*创建75#消息队列*/ do
{ msgrcv(msgqid,&msg,1030,0,0);
/*接收消息*/
printf(“(server)received %ldn”,msg.mtype);sleep(3);}while(msg.mtype!=1);msgctl(msgqid,IPC_RMID,0);/*删除消息队列,归还资源*/ exit(0);}
main(){
server();}
实验结果: