消息队列实现从一个进程向另一个进程发送一个数据块的方法
首先是Comm.h的代码
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define SERVER_TYPE 1
#define CLIENT_TYPE 2
#define SIZE 128
#define PATHNAME "."
#define PROJ_ID 0x666
struct msgbuf{
long mtype;
char mtext[SIZE];
};
int CommMsgQueue(int mgflg);
int CreateMsgQueue();
int GetMsgQueue();
int SendMsg(int msgid, long type, const char *_info);
int RecvMsg();
int DestroyMsgQueue(int msgid);
#endif
Comm.c的代码
#include"Comm.h"
int CommMsgQueue(int msgflg){
key_t key = ftok(PATHNAME,PROJ_ID);//gets key
if(key < 0)//failed
{
perror("ftok");
return -1;
}
int mspid = msgget(key,msgflg);
if(mspid < 0)//failed return -1
{
perror("msgget");
return -2;
}
return mspid;//success return mspid
}
int CreateMsgQueue()
{
return CommMsgQueue(IPC_CREAT | IPC_EXCL | 0666);//must new
}
int GetMsgQueue()
{
return CommMsgQueue(IPC_CREAT);//return has been created
}
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 RecvMsg(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 msgid)
{
if(msgctl(msgid, IPC_RMID, NULL) < 0)
{
perror("msgctl");
return -1;
}
return 0;//success
}
所有的接口已经实现完毕,现在我们分别实现通信双方的代码
首先是server.c
#include"Comm.h"
int main()
{
int msgid = CreateMsgQueue();
printf("msgid: %d\n",msgid);
char buf[SIZE];
while(1)
{
RecvMsg(msgid,CLIENT_TYPE,buf);
printf("client# %s\n",buf);
printf("Please Entry:");
fflush(stdout);
ssize_t _s = read(0,buf,sizeof(buf)-1);
if(_s > 0)
{
buf[_s-1] = '\0';
SendMsg (msgid,SERVER_TYPE,buf);
}
}
DestroyMsgQueue(msgid);
}
接着是client.c
#include"Comm.h"
int main()
{
int msgid = GetMsgQueue();
printf("msgid: %d\n",msgid);
char buf[SIZE];
while(1)
{
printf("Please Entry:");
fflush(stdout);
ssize_t _s = read(0,buf,sizeof(buf)-1);
if(_s > 0)
{
buf[_s-1] = '\0';
}
SendMsg (msgid,CLIENT_TYPE,buf);
RecvMsg(msgid,SERVER_TYPE,buf);
printf("client# %s\n",buf);
}
}
最后我们来看看makefile文件的编写
最后我们来看看结果吧