消息队列实现多人聊天

实验现象:先输入你要发送对象的首字母,即代码中宏定义内容。然后输入你要输入的内容。只能本地通信。
实现流程:首先打开消息队列,创建进程,子进程用于获得键盘输入的内容,像消息队列发送消息。
父进程:按类型从消息队列读取消息,显示读出的信息,打印
 * ************************************************************************/

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <unistd.h>
struct msgbuf
{
long mtype;
char text[100];
char name[20];
};
#define M 'P'//此处为需要发送的对象。
char writer[]="Peter";
int main(int argc, char *argv[])
{
struct msgbuf mybuf;
mybuf.mtype = 1;
char buf[256]="";
int msgqid = msgget((key_t)0326,IPC_CREAT|0666);
if(msgqid < 0)
perror("msgqid");
pid_t pid;
pid = fork();
if(pid<0)
perror("fork");
else if(pid == 0)
{
while(1)
{
printf("%s:",writer);//打印提示符
fflush(stdout);
bzero(buf,sizeof(buf));
if(fgets(buf,sizeof(buf),stdin)== NULL)
exit(-1);
buf[strlen(buf)-1]='\0';
if(buf[0] == 'L' ||buf[0] == 'P' ||buf[0] == 'B')
{
mybuf.mtype = (long)buf[0];//消息类型
strcpy(mybuf.name,writer);
strcpy(mybuf.text,buf+2);//将内容复制过去
if(msgsnd(msgqid,&mybuf,sizeof(mybuf)-sizeof(long),0) != -1)
{
printf("send message success\n");
}else
perror("msgsnd error");
}
}
}
else
{
while(1)
{
msgrcv(msgqid,&mybuf,sizeof(mybuf)-sizeof(long),(long int)M,0);
printf("\rmessage from %s:%s\n",mybuf.name,mybuf.text);
printf("\r%s:",writer);
fflush(stdout);
}
}
return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值