利用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环境下分别编译并运行,即可看到演示效果!!!