makefile
1 .PHONY:all
2 all:cilent server
3 cilent:cilent.c comm.c
4 gcc -o $@ $^
5 server:server.c comm.c
6 gcc -o $@ $^
7
8 .PHONY:clean
9 clean:
10 rm -f cilent server
头文件
1 #ifndef __COMM_H__
2 #define __COMM_H__
3
4 #include<stdio.h>
5 #include<sys/types.h>
6 #include<string.h>
7 #include<sys/ipc.h>
8 #include<sys/msg.h>
9 #define PATHNAME "."
10 #define PROJ_ID 0X6666
11 struct msgbuf{
12 long mtype;
13 char mtext[1024];
14 };
15
16 #define SERVER_TYPE 1
17 #define CLIENT_TYPE 2
18
19 int creatMsgQueue();
20 int destoryMsgQueue();
21 int getMsgQueue();
22 int recvMsg(int msgid,int type,char*_outMsg);
23 int sendMsg(int msgid,int who,const char *msg);
24 #endif //___COMM_H__
函数文件
1 #include"comm.h"
2
3
4 static int commMsgQueue(int flag)
5 {
6 key_t key=ftok(PATHNAME,PROJ_ID);
7
8 if(key<0)
9 {
10 perror("ftok");
11 return-1;
12 }
13 int msgid=0;
14 msgid=msgget(key,flag);
15 if(msgid<0)
16
17 {
18 perror("msgget");
19 return -2;
20 }
21
22 return msgid;
23 }
24 int recvMsg(int msgid,int type,char*_outMsg)
25 {
26 struct msgbuf _mb ;
27 if(msgrcv(msgid,&_mb,sizeof(_mb.mtext),type,0)<0)
28 {
29 perror("msgrcv");
30 return -1;
31 } 32 strcpy(_outMsg,_mb.mtext);
33 return 0;
34 }
35 int sendMsg(int msgid,int who,const char *msg)
36 {
37 struct msgbuf _mb;//创建结构体
38 _mb.mtype=who;//给类型赋值
39 strcpy(_mb.mtext,msg);//给内容赋值,必须用strcpy
40 if(msgsnd(msgid,(void*)&_mb,sizeof(_mb.mtext),0)<0)
41 {
42 perror("magsnd");
43 return -1;
44 }
45 return 0;
46 }
int creatMsgQueue()
50 {
51 return commMsgQueue(IPC_CREAT|IPC_EXCL|0666);
52 }
53 int getMsgQueue()
54 {
55 return commMsgQueue(IPC_CREAT);
56 }
57 int destoryMsgQueue(int msgid)
58 {
59 if(msgctl(msgid,IPC_RMID,NULL)<0)//IPC_RMID表示立刻删除
60 {
61 perror("msgctl");
62 return -1;
63 }
64 }
服务器端
1 #include"comm.h"
2 int main ()
3 {
4 char buf [1024];
5 int ret=0;
6 ret=creatMsgQueue();//创建消息队列
7
8 printf("ret=%d\n",ret);
9 while(1)
10 {
11 recvMsg(ret,CLIENT_TYPE,buf);//接受,buf为返回型参数
12 printf("cilent say#%s\n",buf);
13 fflush(stdout);
14 ssize_t s=read(0,buf,sizeof(buf)-1);
15 if(s>0)
16 {
17 buf[s-1]=0;
18 sendMsg(ret,SERVER_TYPE,buf);
19 }
20
21 }
22
23
24 destoryMsgQueue(ret);
25 // sendMsg(ret,SERVER_TYPE,"hello mdg queue!\n");
26
27
28 return 0;
29 }
客户端
1 #include"comm.h"
2 int main ()
3 {
4 int msgid=getMsgQueue();//存在则打开,不存在则创建
5 printf("msgid=%d\n",msgid);
6 char buf [1024];
7 while(1)
8 {
9 printf("Please Enter#");//避免换行。采用内存刷新
10 fflush(stdout);
11 ssize_t s=read(0,buf,sizeof(buf)-1);//从键盘输入读取到buf
12 if(s>0)
13 {
14 buf[s-1]=0;
15 sendMsg(msgid,CLIENT_TYPE,buf);//将buf内容发送
16 }
17 recvMsg(msgid,SERVER_TYPE,buf);//接受返回型参数buf的值
18 printf("server say#%s\n",buf);
19 }
20
21
22 destoryMsgQueue(msgid);//销毁
23 // sendMsg(ret,SERVER_TYPE,"hello mdg queue!\n");
24
25
26 return 0;
27 }
28