comm.h
#ifndef __COMM_H__
#define __COMM_H__
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<unistd.h>
#include<string.h>
#define PATHNAME "./"
#define PROJ_ID 0x666
#define SIZE 128
#define SERVER_SIZE 1
#define CLIENT_SIZE 2
struct msgbuf
{
long mtype;
char mtext[SIZE];
};
int commMsgQueue(int flags);
int createMsgQueue();
int getMsgQueue();
int sendMSg(int msgid,long type,const char*_info);
int recMsg(int msgid,long type,char out[]);
int destroyMsgQueue(int msg_id);
#endif
comm.c
#include "comm.h"
int commMsgQueue(int flags)
{
umask(0);
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("msgget");
return -2;
}
return msg_id;
}
int createMsgQueue()
{
return commMsgQueue(IPC_CREAT|IPC_EXCL|0x666);
}
int getMsgQueue()
{
return commMsgQueue(IPC_CREAT);
}
int sendMSg(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)
{
perror("msgsnd");
return -1;
}
return 0;
}
int recMsg(int msgid,long type,char out[])
{
struct msgbuf msg;
if(msgrcv(msgid,&msg,sizeof(msg.mtext),type,0) < 0)
{
perror("msgrcv");
return -1;
}
strcpy(out,msg.mtext);
return 0;
}
int destroyMsgQueue(int msg_id)
{
if(msgctl(msg_id,IPC_RMID,NULL) < 0)
{
perror("msgctl");
return -1;
}
return 0;
}
server.c
#include"comm.h"
//#include"comm.c"
int main()
{
int msgid = getMsgQueue();
char buf[SIZE];
while(1)
{
printf("please Enter$ ");
fflush(stdout);
size_t s = read(0,buf,sizeof(buf)-1);
if(s > 0)
{
buf[s - 1] ='\0';
sendMSg(msgid,CLIENT_SIZE,buf);
}
recMsg(msgid,SERVER_SIZE,buf);
printf("server# %s\n ",buf);
}
return 0;
}
client.c
#include"comm.h"
#include"comm.c"
int main()
{
int msgid = createMsgQueue();
printf("msgid : %d\n",msgid);
long type = SERVER_SIZE;
char buf[SIZE];
while(1)
{
recMsg(msgid,CLIENT_SIZE,buf);
printf("client# %s\n",buf);
printf("please Enter$ ");
fflush(stdout);
size_t s = read(0,buf,sizeof(buf));
if(s > 0)
{
buf[s - 1] ='\0';
sendMSg(msgid,SERVER_SIZE,buf);
}
sleep(1);
}
sleep(5);
destroyMsgQueue(msgid);
return 0;
}