设为首页 加入收藏

TOP

简单的Linux 消息队列测试代码
2014-11-24 11:50:20 来源: 作者: 【 】 浏览:0
Tags:简单 Linux 消息 队列 测试 代码

简单的Linux 消息队列测试代码:


/*msg_block_read.c*/


#include
#include
#include
#include
#include
#include


struct msg_buf
{
int mtype;
// char aaa[255]; //此结构体只能包含两个成员
char data[255];
};

int main()
{
key_t key;
int msgid;
int ret;
struct msg_buf msgbuf;

key=ftok("/tmp/2",'a');
printf("key =[%x]\n",key);
msgid=msgget(key,IPC_CREAT|0666); /* */

if(msgid==-1)
{
printf("create error\n");
return -1;
}
/*
msgbuf.mtype = getpid();
strcpy(msgbuf.data,"test haha, aaaaaaaaaaaaaaaaaa");
ret=msgsnd(msgid,&msgbuf,strlen(msgbuf.data),0);
if(ret==-1)
{
printf("send message err\n");
return -1;
}
*/
memset(&msgbuf,0,sizeof(msgbuf));
ret=msgrcv(msgid,&msgbuf,sizeof(msgbuf.data),0,0); //阻塞读取,第一个消息
if(ret==-1)
{
printf("recv message err\n");
return -1;
}
printf("recv msg =[%s], len = %d\n",msgbuf.data, strlen(msgbuf.data));

}



/*msg_block_write.c*/


#include
#include
#include
#include
#include
#include


struct msg_buf
{
int mtype;
// char aaa[255]; //此结构体只能包含两个成员
char data[255];
};

int main()
{
key_t key;
int msgid;
int ret;
struct msg_buf msgbuf;

key=ftok("/tmp/2",'a');
printf("key =[%x]\n",key);
msgid=msgget(key,IPC_CREAT|0666); /* */

if(msgid==-1)
{
printf("create error\n");
return -1;
}

msgbuf.mtype = getpid();
strcpy(msgbuf.data,"test haha, aaaaaaaaaaaaaaaaaa");
ret=msgsnd(msgid,&msgbuf,strlen(msgbuf.data),0); // 阻塞发送
if(ret==-1)
{
printf("send message err\n");
return -1;
}
/*
memset(&msgbuf,0,sizeof(msgbuf));
ret=msgrcv(msgid,&msgbuf,sizeof(msgbuf.data),getpid(),0);
if(ret==-1)
{
printf("recv message err\n");
return -1;
}
printf("recv msg =[%s], len = %d\n",msgbuf.data, strlen(msgbuf.data));
*/
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux system V IPC 信号灯和共享.. 下一篇Android应用ANR事件分析指导

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Bash 脚本教程——Li (2025-12-26 07:53:35)
·实战篇!Linux shell (2025-12-26 07:53:32)
·整理了250个shell脚 (2025-12-26 07:53:29)
·HyperText Transfer (2025-12-26 07:20:48)
·半小时搞懂 HTTP、HT (2025-12-26 07:20:42)