comm.h
#ifndef _COMM_H_
#define _COMM_H_
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
#define PATHNAME "."
#define PROJ_ID 0x666
#define SIZE 128
#define SERVER_TYPE 1
#define CLIENT_TYPE 2
struct msgbuf
{
long mtype;
char mtext[SIZE];
};
int createMsgQueue();//创建消息队列
int getMsgQueue();//获取消息队列
int recvMsgQueue(int msg,long type,char out[]);//接收消息
int sendMsgQueue(int msgid,long type,const char* _info);//发送消息
int destroyMsgQueu1e(int msgid);//销毁消息队列
#endif
comm.c
#include"comm.h"
int commMsgQueue(int flags)
{
key_t _k = ftok(PATHNAME,PROJ_ID);//创建消息队列
if(_k<0)
{
perror("ftok");
return -1;
}
int msg_id = msgget(_k,flags);
if(msg_id<0)
{
perror("msg");
return -2;
}
return msg_id;
}
int createMsgQueue()
{
return commMsgQueue(IPC_CREAT|IPC_EXCL|0666 );
}
int getMsgQueue()
{
return commMsgQueue(IPC_CREAT );
}
int recvMsgQueue(int msgid,long type,char out[])
{
struct msgbuf msg;
if(msgrcv(msgid,&msg,sizeof(msg.mtext),type,0)<0)//函数msgrcv()
{
perror("msgrcv");
return -1;
}
strcpy(out,msg.mtext);
return 0;
}
int sendMsgQueue(int msgid,long type,const char *_info)
{
struct msgbuf msg;
msg.mtype = type;
strcpy(msg.mtext,_info);
if( msgsnd(msgid,&msg,sizeof(msg.mtext),0)<0)//函数msgsnd()
{
perror("msgsnd");
return -1;
}
return 0;
}
int destroyMsgQueue(int msgid)
{
if(msgctl(msgid,IPC_RMID,NULL)<0)//函数msgctl()
{
perror("msgctl");
return -1;
}
return 0;
}
server.c
#include"comm.h"
int main()
{
int msgid = createMsgQueue();
printf("msgid:%d\n",msgid);
char buf[SIZE];
while(1)
{
recvMsgQueue(msgid,CLIENT_TYPE,buf);//server端收到的消息类型为client
printf("client#%s\n",buf);
printf("please enter$");
fflush(stdout);
ssize_t s=read(0,buf,sizeof(buf)-1);
if(s>0)
{
buf[s-1] = '\0';
sendMsgQueue( msgid,SERVER_TYPE,buf);//发送server类型的消息
}
}
destroyMsgqueue(msgid);
return 0;
}
client.c
#include"comm.h"
int main()
{
int msgid = getMsgQueue();
printf("msgid:%d\n",msgid);
char buf[SIZE];
while(1)
{
printf("please enter$");
fflush(stdout);
ssize_t s = read(0,buf,sizeof(buf)-1);
if(s>0)
{
buf[s-1] = '\0';
sendMsgQueue( msgid,CLIENT_TYPE,buf);//client端发送client类型的消息
}
recvMsgQueue(msgid,SERVER_TYPE,buf);//client端收到server类型的消息
printf("server#%s\n",buf);
}
return 0;
}