消息队列就是用来进程间通信的, 每个进程只要知道消息队列的queueID即可
#ifndef CMSGOP_H
#define CMSGOP_H
#include
#include
#include
class CMsgOp
{
public:
CMsgOp();
virtual ~CMsgOp();
typedef struct _customMessageFormat{
int processID;
int cmd;
int commandArg;
}CCustomMessageFormat;
int init();
int send(const CCustomMessageFormat &message);
int receive(CCustomMessageFormat &message);
private:
int msgQueueID;
struct msgbuf sendBuf;
struct msgbuf recvBuf;
};
#endif // CMSGOP_H
#include "cmsgop.h"
#include
#include
#include
CMsgOp::CMsgOp()
{
}
CMsgOp::~CMsgOp()
{
msgctl(msgQueueID, IPC_RMID, NULL);
}
int CMsgOp::init()
{
key_t key = ftok("/home/maemo/tmp2", 1);
if(-1 == key)
{
perror("ftok failed!");
return -1;
}
int ret = msgget(key, IPC_CREAT);
if(-1 == ret)
{
perror("create message queue failed!");
return -1;
}
msgQueueID = ret;
return 0;
}
int CMsgOp::send(const CCustomMessageFormat &message)
{
memcpy(sendBuf.mtext, &message, sizeof(CCustomMessageFormat));
sendBuf.mtype = 1;
int ret = msgsnd(msgQueueID, &sendBuf, sizeof(CCustomMessageFormat), 0);
if(-1 == ret)
{
perror("message send failed!");
return ret;
}
}
int CMsgOp::receive(CCustomMessageFormat &message)
{
int ret = msgrcv(msgQueueID, &recvBuf, sizeof(CCustomMessageFormat), 0, IPC_NOWAIT);
if(-1 == ret)
{
perror("receive message failed!");
return -1;
}
memcpy(&message, recvBuf.mtext, sizeof(CCustomMessageFormat));
return ret;
}
取消
评论