Linux消息队列的使用演示

利用Linux消息队列实现本地聊天室,练习所用,不喜勿喷!!!

分别有两位角色Jack和Rose,双方互相通信

Jack.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

#define J2R 100
#define R2J 200

struct mymsg{
	long mtype;
	char mtext[64];
};

void readmsg(int msgid)
{
	struct mymsg buf;
	buf.mtype = R2J;//设置接收指定数据类型
	while(1)
	{
		bzero(buf.mtext,sizeof(buf.mtext));
		if(msgrcv(msgid,&buf,sizeof(buf.mtext),buf.mtype,IPC_NOWAIT)>0)//接收信息数大于0显示信息
		{
			printf("\rRose said:%s\nI said:",buf.mtext);
			fflush(stdout);
		}
	}
}

void writemsg(int msgid,int p)
{
	struct mymsg buf;
	buf.mtype = J2R;//设置发送数据类型
	while(1)
	{
		bzero(buf.mtext,sizeof(buf.mtext));//输入exit退出
		printf("I said:");
		fgets(buf.mtext,64,stdin);
		strtok(buf.mtext,"\n");
		if(strncmp(buf.mtext,"exit",4)==0)
		{
			kill(p,SIGINT);
			return;
		}
		msgsnd(msgid,&buf,sizeof(buf.mtext),IPC_NOWAIT);
		
	}
}
int main()
{
	key_t key = ftok(".",100);//生成消息队列key值
	
	int msgid = msgget(key,IPC_CREAT|0666);//生成消息队列ID值
	
	pid_t p = fork();//生成父子进程,子进程用于接受信息,父进程用于发送信息
	
	if(p == 0)//child used to read
	{
		readmsg(msgid);
	}
	else
	{
		writemsg(msgid,p);
		wait(NULL);
		msgctl(msgid,IPC_RMID,NULL);
	}
	
	return 0;
}

 

Rose.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

#define J2R 100
#define R2J 200

struct mymsg{
	long mtype;
	char mtext[64];
};

void readmsg(int msgid)
{
	struct mymsg buf;
	buf.mtype = J2R;//设置接收指定数据类型
	while(1)
	{
		bzero(buf.mtext,sizeof(buf.mtext));
		if(msgrcv(msgid,&buf,sizeof(buf.mtext),buf.mtype,IPC_NOWAIT)>0)//接收信息数大于0显示信息
		{
			printf("\rJack said:%s\nI said:",buf.mtext);
			fflush(stdout);
		}
	}
}

void writemsg(int msgid,int p)
{
	struct mymsg buf;
	buf.mtype = R2J;//设置发送数据类型
	while(1)
	{
		bzero(buf.mtext,sizeof(buf.mtext));
		printf("I said:");
		fgets(buf.mtext,64,stdin);
		strtok(buf.mtext,"\n");
		if(strncmp(buf.mtext,"exit",4)==0)//输入exit退出
		{
			kill(p,SIGINT);
			return;
		}
		msgsnd(msgid,&buf,sizeof(buf.mtext),IPC_NOWAIT);
		
	}
}
int main()
{
	key_t key = ftok(".",100);//生成消息队列key值
	
	int msgid = msgget(key,IPC_CREAT|0666);//生成消息队列ID值
	
	pid_t p = fork();//生成父子进程,子进程用于接受信息,父进程用于发送信息
	
	if(p == 0)//child used to read
	{
		readmsg(msgid);
	}
	else
	{
		writemsg(msgid,p);
		wait(NULL);
		msgctl(msgid,IPC_RMID,NULL);
	}
	
	
	return 0;
}

Linux环境下分别编译并运行,即可看到演示效果!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值