码迷,mamicode.com
首页 > 其他好文 > 详细

消息队列实现即时通讯

时间:2015-05-13 23:18:51      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:linux   linux内核   

</pre>发送端和接收端都可以发送和接收信息,只是发送和接收消息的类型不同,一个是1,一个是2.具体代码如下:<p></p><p></p><pre code_snippet_id="666150" snippet_file_name="blog_20150513_3_8263799" name="code" class="cpp"><pre code_snippet_id="666150" snippet_file_name="blog_20150513_2_5260248" name="code" class="cpp">//发送端
#include<stdio.h>#include<stdlib.h>#include<sys/ipc.h>#include<sys/msg.h>#include<string.h>struct msgbuf{int type;char ptr[0];};int main(int argc,char *argv[]){key_t key;key=ftok(argv[1],100);int msgid;msgid=msgget(key,IPC_CREAT|0600);pid_t pid;pid=fork();if(pid==0){while(1){printf("pls input msg to send:");char buf[128];fgets(buf,128,stdin);struct msgbuf *ptr=malloc(sizeof(struct msgbuf)+strlen(buf)+1);ptr->type=1;memcpy(ptr->ptr,buf,strlen(buf)+1);msgsnd(msgid,ptr,strlen(buf)+1,0);free(ptr);}}else{struct msgbuf{int type;char ptr[1024];};while(1){struct msgbuf mybuf;memset(&mybuf,‘\0‘,sizeof(mybuf));msgrcv(msgid,&mybuf,1024,2,0); printf("recv msg:%s\n",mybuf.ptr);}}}



//接收端

#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
struct msgbuf{
	int type;
	char ptr[0];
};
int main(int argc,char *argv[])
{
	key_t key;
	key=ftok(argv[1],100);

	int msgid;
	msgid=msgget(key,IPC_CREAT|0600);

	pid_t pid;
	pid=fork();
	if(pid==0)	//send
	{
		while(1)
		{
			printf("pls input msg to send:");
			char buf[128];
			fgets(buf,128,stdin);
			struct msgbuf *ptr=malloc(sizeof(struct msgbuf)+strlen(buf)+1);
			ptr->type=2;	//send msg type=2
			memcpy(ptr->ptr,buf,strlen(buf)+1);
			msgsnd(msgid,ptr,strlen(buf)+1,0);
			free(ptr);
		}
	}
	else
	{
		struct msgbuf{
			int type;
			char ptr[1024];
		};
		while(1)
		{
			struct msgbuf mybuf;
			memset(&mybuf,'\0',sizeof(mybuf));
			msgrcv(msgid,&mybuf,1024,1,0);	//recv msg type=2
			printf("recv msg:%s\n",mybuf.ptr);
		}
	}
}



消息队列实现即时通讯

标签:linux   linux内核   

原文地址:http://blog.csdn.net/u013467442/article/details/45700957

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!