struct ipc_perm {
key_t __key; /* ftok所获取的唯一标识的key值*/
uid_t uid; /* 拥有者的有效uid*/
gid_t gid; /* 拥有者的有效gid */
uid_t cuid; /* 创建者的有效uid*/
gid_t cgid; /* 创建者的有效gid */
unsigned short mode; /* 权限 */
unsigned short __seq; /* 序列号*/
int msgget(key_t key,int msgflag);
int msgsnd(int msgid,const void* msgp,size_t msgsz,int msgflg);
ssize_t msgrgv(int msgid,const void* msgp,size_t msgsz,long msgtyp,int msgflg);
int msgctl(int msgid,int cmd,struct msqid_ds *buf);
//comm.h
#include
#include
#include
#include
#include
#define PATHNAME "."
#define PROJ_ID 0x6666
#define SERVER_TYPE 1
#define CLIENT_TYPE 2
struct msgbuf {
long mtype;
char mtext[1024];
};
int createMsgqueue();
int getMsg();
int destroyMsg(int msgid);
int recvMsg(int msgid,long recvtype,char out[]);
int sendMsg(int msgid,long who,char* msg);
#endif //_COMM_H
//comm.c
#include"comm.h"
int commMsgqueue(int flags)
{
key_t _key = ftok(PATHNAME,PROJ_ID);
if(_key < 0)
{
perror("ftok");
return -1;
}
int msgid = msgget(_key,flags);
if(msgid < 0)
{
perror("msgget");
return -2;
}
return msgid;
}
int createMsgqueue()
{
return commMsgqueue(IPC_CREAT | IPC_EXCL|0666);
}
int getMsg()
{
return commMsgqueue(IPC_CREAT);
}
int destroyMsg(int msgid)
{
if(msgctl(msgid,IPC_RMID,NULL) < 0)
{
perror("msgctl");
return -1;
}
return 0;
}
int recvMsg(int msgid,long recvtype,char out[])
{
struct msgbuf buf;
if(msgrcv(msgid,(void*)&buf,sizeof(buf.mtext),recvtype,0) < 0)
{
perror("msgrcv");
return -1;
}
strcpy(out,buf.mtext);
return 0;
}
int sendMsg(int msgid,long who,char* msg)
{
struct msgbuf buf;
buf.mtype=who;
strcpy(buf.mtext,msg);
if(msgsnd(msgid,(void*)&buf,sizeof(buf.mtext),0) < 0)
{
perror("msgsnd");
return -1;
}
return 0;
}
//server.c
#include"comm.h"
#include
int main()
{
int msgid = createMsgqueue();
char buf[1024];
while(1)
{
buf[0]=0;
recvMsg(msgid,CLIENT_TYPE,buf);
printf("client# %s\n",buf);
printf("please Enter# ");
fflush(stdout);
ssize_t s = read(0,buf,sizeof(buf));
if(s > 0)
{
buf[s-1] = 0;
sendMsg(msgid,SERVER_TYPE,buf);
printf("send done,wait recv...\n");
}
}
destroyMsg(msgid);
return 0;
}
//client.c
#include"comm.h"
#include
int main()
{
int msgid = createMsgqueue();
char buf[1024];
while(1)
{
buf[0]=0;
recvMsg(msgid,CLIENT_TYPE,buf);
printf("client# %s\n",buf);
printf("please Enter# ");
fflush(stdout);
ssize_t s = read(0,buf,sizeof(buf));
if(s > 0)
{
buf[s-1] = 0;
sendMsg(msgid,SERVER_TYPE,buf);
printf("send done,wait recv...\n");
}
}
destroyMsg(msgid);
return 0;
}
[xiaoxu@bogon msgqueue]$ cat client.c
#include
#include"comm.h"
int main()
{
int msgid = getMsg();
char buf[1024];
while(1)
{
buf[0]=0;
printf("please Enter# ");
fflush(stdout);
ssize_t s = read(0,buf,sizeof(buf));
if(s > 0)
{
buf[s-1] = 0;
sendMsg(msgid,CLIENT_TYPE,buf);
printf("send done,wait recv...\n");
}
recvMsg(msgid,SERVER_TYPE,buf);
printf("server# %s\n",buf);
}
return 0;
}
//Makefile
.PHONY:all
all:client server
client:client.c comm.c
gcc -o $@ $^
server:server.c comm.c
gcc -o $@ $^
.PHONY:clean
clean:
rm -f server client