共享内存问题 急!!!!
。H文件:
/*内部消息*/
struct CMsg
{
int nMsgTo; /*消息目的结点*/
int nMsgFrom; /*消息源结点*/
unsigned char nSize; /*消息体大小*/
char szData[MAX_PACKET_SIZE]; /*消息体*/
CMsg& operator=(const CMsg &stMsg)
{
nMsgTo = stMsg.nMsgTo;
nMsgFrom = stMsg.nMsgFrom;
nSize = stMsg.nSize;
memcpy(szData, stMsg.szData, nSize);
return *this;
}
};
/***********************************
共享内存类
***********************************/
class CShm
{
public:
CShm(int nKey, int nSize);
~CShm();
void GetShm();
void AttachShm();
void DetachShm();
void RemoveShm();
void InitShm();
char* GetData(){return m_pData;}
protected:
int m_nKey;
int m_nSize;
int m_nShmID;
char* m_pData;
bool m_bCreate;
};
/***********************************
信号量类
***********************************/
#if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED)
/* union semun is defined by including <sys/sem.h> */
#else
/* according to X/OPEN we have to define it ourselves */
union semun {
int val; /* value for SETVAL */
struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */
unsigned short int *array; /* array for GETALL, SETALL */
struct seminfo *__buf; /* buffer for IPC_INFO */
};
#endif
class CSem
{
public:
CSem(int nKey, int nCount = 1);
~CSem();
bool Lock(int nIndex);
bool Unlock(int nIndex);
void GetSem();
void RemoveSem();
void InitSem();
void SetValue(int nSemNum, int nValue);
int GetValue(int nSemNum);
protected:
int m_nKey;
int m_nSemCount;
int m_nSemID;
bool m_bCreate;
};
/*自定义消息队列*/
struct CQueueShm
{
int nCount;
int nStackTop;
int nIdx[MAX_QUEUE_ITEM];
int nStack[MAX_QUEUE_ITEM];
CMsg stItems[MAX_QUEUE_ITEM];
CMsg& operator[](int nIndex)
{
return stItems[nIdx[nIndex]];
}
};
class CMyMsgQueue : public CShm
{
public:
CMyMsgQueue(int nKey, int nSemKey);
~CMyMsgQueue();
public:
bool Write(CMemoryStream &Stream, int nMaxRepeate = 60);
bool Read(CMemoryStream &Stream, int nSize, int nMsgType = 0);
inline int GetCount(){return m_pShm->nCount;}
void Clear();
void Lock();
void UnLock();
void GetMsgQueue(){}
private:
int GetCmdByIndex(int nIndex);
int FindCmd(int nCmd);
bool InterWrite(CMemoryStream &Stream);
int FindPos(int nCmd, int &nState);
void InitSlot();
int AllocSlot();
void FreeSlot(int nIndex);
private:
CQueueShm *m_pShm;
CSem m_MsgSem;
};