话不多说,看代码!
一、框架
二、服务器代码
#include<unistd.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#define ERR_EXIT(m)\
do \
{ \
perror(m); \
exit(EXIT_FAILURE);\
}while(0);
#define MSGMAX 8192
struct msgbuf {//消息缓冲区
long mtype; //消息类型,从消息队列中读取消息的一个重要依据就是消息的类型
char mtext[MSGMAX]; //消息内容
};
void echo_srv(int msgid)
{
int n;
struct msgbuf msg;
memset(&msg,0,sizeof(msg));
while(1)
{
if((n=msgrcv(msgid,&msg,MSGMAX,1,0))<0) ERR_EXIT("msgsnd");//从消息队列中取出消息
int pid;
pid=*((int *)msg.mtext);//把消息队列中前4个字节取出来,假设作为进程号码
fputs(msg.mtext+4,stdout);//stdout表示标准的输出,输出到屏幕上
msg.mtype=pid;
msgsnd(msgid,&msg,n,0);//回射
}
}
int main(int argc, char *argv[])
{
int msgid;
msgid=msgget(1234,IPC_CREAT | 0666);//创建消息队列
if(msgid==-1) ERR_EXIT("msgget");//判断是否创建成功
echo_srv(msgid);//调用回射服务
return 0;
}
三、客户端代码
#include<unistd.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
#define ERR_EXIT(m)\
do \
{ \
perror(m); \
exit(EXIT_FAILURE);\
}while(0);
#define MSGMAX 8192
struct msgbuf {//消息缓冲区
long mtype; //消息类型,从消息队列中读取消息的一个重要依据就是消息的类型
char mtext[MSGMAX]; //消息内容
};
void echo_cli(int msgid)
{
int pid;
pid=getpid();//获取进程号,要把进程号也发送过去
int n;
struct msgbuf msg;
memset(&msg,0,sizeof(msg));
*((int *)msg.mtext)=pid;
msg.mtype=1;//类型为1,代表
while(fgets(msg.mtext+4,MSGMAX,stdin)!=NULL)//不断从键盘获取数据
{
if((n=msgsnd(msgid,&msg,4+strlen(msg.mtext+4),0))<0) ERR_EXIT("msgsnd");//向消息队列发送消息
memset(msg.mtext+4,0,MSGMAX-4);//把接收到的内容先清空
if((n=msgrcv(msgid,&msg,MSGMAX,pid,0))<0) ERR_EXIT("msgsnd");//从消息队列中取出消息
fputs(msg.mtext+4,stdout);//把接收到的消息打印出来
memset(msg.mtext+4,0,MSGMAX-4);
}
}
int main(int argc, char *argv[])
{
int msgid;
msgid=msgget(1234,0);//打开一个消息队列
if(msgid==-1) ERR_EXIT("msgget");//判断是否创建成功
echo_cli(msgid);//调用回射客户端
return 0;
}