文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>消息队列的使用

消息队列的使用

时间:2010-12-02  来源:bluesky2254

源码:  
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
typedef struct
{
int msg_type;
char msg_data[512];
} msgstr;
main()
{
int key = 4000;
int msgid = 0;
int msgid1 = 0;
//int msgid2 = 0;
int i=0,j=0;
msgstr send_msg,recv_msg;
//创建消息队列的第一个节点
msgid = msgget(key,IPC_CREAT|0660);
if(msgid < 0)
printf("message 1 create fail[msgid = %d]\n",msgid);
else
printf("message 1 create success[msgid = %d]\n",msgid);
//创建消息队列的第二个节点
msgid1 = msgget(key+100,IPC_CREAT|0660);
if(msgid1 < 0)
printf("message 2 create fail[msgid1 = %d]\n",msgid);
else
printf("message 2 create success[msgid1 = %d]\n",msgid);
//发送第一个节点消息
send_msg.msg_type = 100;
memset(send_msg.msg_data,0,512);
strcpy(send_msg.msg_data,"This is my first message.");
i = msgsnd(msgid,&send_msg,512,0);
if(i == 0)
printf("message 1 send success!\n");
else
printf("message 1 send failed!\n");
//发送第二个节点消息
send_msg.msg_type = 200;
memset(send_msg.msg_data,0,512);
strcpy(send_msg.msg_data,"This is my second message.");
i = msgsnd(msgid1,&send_msg,512,0);
if(i == 0)
printf("message 2 send success!\n");
else
printf("message 2 send failed!\n");
//发送第三个节点消息
send_msg.msg_type = 300;
memset(send_msg.msg_data,0,512);
strcpy(send_msg.msg_data,"This is my third message.");
i = msgsnd(0,&send_msg,512,0);
if(i == 0)
printf("message 3 send success!\n");
else
printf("message 3 send failed!\n");
//接收第一个节点消息
recv_msg.msg_type = 0;
memset(recv_msg.msg_data,0,sizeof(recv_msg.msg_data));
j = msgrcv(msgid,&recv_msg,512,0,IPC_NOWAIT);
if(j <= 0)
printf("message receive failed\n");
else
{
printf("message receive success[length: %d]\n",j);
printf("message type = %d\n",recv_msg.msg_type);
printf("message char data: %s\n",recv_msg.msg_data);
}
//接收第二个节点消息
recv_msg.msg_type = 0;
memset(recv_msg.msg_data,0,sizeof(recv_msg.msg_data));
j = msgrcv(msgid1,&recv_msg,512,0,IPC_NOWAIT);
if(j <= 0)
printf("message receive failed\n");
else
{
printf("message receive success[length: %d]\n",j);
printf("message type = %d\n",recv_msg.msg_type);
printf("message char data: %s\n",recv_msg.msg_data);
}
}
 
运行结果:
 
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载