msg_server.c
#include "comm.h"
int main()
{
int msg_id=create_msg_queue();
char buf[_SIZE_];
while(1)
{
memset(buf,0,sizeof(buf));
printf("please enter >:");
fgets(buf,sizeof(buf)-1,stdin);
if( strncmp(buf,"quit",4)==0)
{
printf("server bye!\n");
break;
}
send_msg(msg_id,ser_send_type,buf);
memset(buf,0,sizeof(buf));
recv_msg(msg_id,cli_send_type,buf);
printf("client:%s",buf);
}
destroy_msg(msg_id);
return 0;
}
msg_client.c
#include"comm.h"
int main()
{
int msg_id=get_msg_queue();
if(msg_id < 0){
return 1;
}
char buf[_SIZE_];
while(1)
{
recv_msg(msg_id,ser_send_type,buf);
printf("server:%s",buf);
memset(buf,0,sizeof(buf));
printf("please enter:");
fgets(buf,sizeof(buf)-1,stdin);
if(strncmp(buf,"quit",4)==0)
{
printf("client bye!\n");
break;
}
send_msg(msg_id,cli_send_type,buf);
}
destroy_msg(msg_id);
return 0;
}
comm.c
#include"comm.h"
const int ser_send_type=1;//server
const int cli_send_type=2;//client
int comm_msg_queue(int flag)
{
key_t key = ftok(_PATH_NAME_,_PROJ_ID_);
if(key == -1)
{
perror("ftok");
return -2;
}
int msg_id=msgget(key,flag);
if(msg_id<0)
perror("msgget");
return msg_id;
}
int create_msg_queue()
{
int flag=IPC_CREAT|IPC_EXCL|0664;
return comm_msg_queue(flag);
}
int get_msg_queue()
{
int flag=IPC_CREAT;
return comm_msg_queue(flag);
}
int recv_msg(int msg_id,int type,char* out)
{
msg_t msg;
msg.mtype=type;
size_t ret=msgrcv(msg_id,&msg,sizeof(msg.mtext),type,0);
if(ret<0)
{
perror("msgrcv");
return 1;
}
strcpy(out,msg.mtext);
return 0;
}
int send_msg(int msg_id,int type,char* msg_in)
{
msg_t msg;
msg.mtype=type;
strncpy(msg.mtext,msg_in, strlen(msg_in)+1);
size_t ret=msgsnd(msg_id,&msg,sizeof(msg.mtext),0);
if(ret<0)
{
perror("msgsnd");
return 2;
}
return 0;
}
int destroy_msg(int msg_id)
{
msgctl(msg_id,IPC_RMID,NULL);
}
comm.h
#pragma once
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include <sys/types.h>
#include<time.h>
extern const int ser_send_type;//server
extern const int cli_send_type;//client
#define _PATH_NAME_ "/tmp"
#define _PROJ_ID_ 0x111
#define _SIZE_ 512
int create_msg_queue();
int get_msg_queue();
int recv_msg(int msg_id,int type,char* out);
int send_mag(int msg_id,int type,char* in);
typedef struct msgbuf
{
long mtype;
char mtext[_SIZE_];
} msg_t;
makefile
.PHONY: all clean
all:msg_server msg_client
msg_server:msg_server.o comm.o
gcc -o $@ $^
msg_client:msg_client.o comm.o
gcc -o $@ $^
%.o:%.c
gcc -c $<
clean:
rm -rf msg_server msg_client *.o
编译直接执行make,然后会生成两个可执行程序.
都是根据消息的类型从消息队列中获取对应的消息