日期:2014-05-16  浏览次数:20732 次

消息队列收不到消息
我在程序启动的时候创建了两个线程和一个消息队列。一个线程把收到的数据发给另一个线程。

//我的数据封装
struct mymsgbuf
{
  long msg_type;//消息类型
int nCurSeqNo;//丢包计数器0
short *pData;
int threadnumber; //线程数标号
};


实际调用:msg_create(g_MsgSqid); //创建消息队列

//创建消息队列
int CMessage::msg_create(int msgSqid )
{
 key_t key;
 key = IPC_PRIVATE;

 int gflags;//rflags;
 gflags=IPC_CREAT|IPC_EXCL; //IPC_EXCL如果队列已存在,则失败
 msgSqid = msgget(key,gflags|00666);//创建一个新的消息队列,返回消息队列标识符

  if(msgSqid == -1)
 {
  printf("msg create error\r\n");
  return 1;
 }
  return msgSqid;//得到了队列标识符,我们就可以在队列上执行我们希望的操作
}
实际调用:sendMessage(g_MsgSqid,10,&m_recvmsgdata);//发送消息至处理线程

//发送消息
void CMessage::sendMessage(int msgSqid,long type,struct mymsgbuf *msg_sbuf)
{
  int sflags = IPC_NOWAIT;

  msg_sbuf->msg_type = type;

  int length = sizeof(mymsgbuf) - sizeof(long);

  int reval = msgsnd(msgSqid,&msg_sbuf,length,sflags);

  if(reval == -1)
  {
  printf("message send error\n");
  }
}
实际调用:recvMessage(g_MsgSqid,10,mymsgrbuf);//接收到数据存于mymsgrbuf
//接收
 void CMessage::recvMessage(int msgSqid,long type,struct mymsgbuf *msg_rbuf)
 {
  int rflags=IPC_NOWAIT|MSG_NOERROR;

  /*The length is essentially the size of the structure minus sizeof(mtype)*/
  int length = sizeof(struct mymsgbuf)-sizeof(long);
  int reval = msgrcv(msgSqid,msg_rbuf,length,type,rflags);//c从消息队列接收消息,type为将要从消息队列中读取的消
  if(reval == -1)//返回复制到消息缓冲区的字节数
  {
  printf("read msg error\n"); //接收不到数据!!!!!!!!!!!

  if(errno == ENOMSG)
  printf("8\n");

  }

  else
  printf("read from msg queue %d bytes\n",reval);
 }
现在的问题是接收不到数据,errno == ENOMSG。但我的数据类型没错啊。。。。


------解决方案--------------------
非阻塞recv,你确定是你希望的?
------解决方案--------------------
C/C++ code

IPC_NOWAIT标志被设置,函数将会立刻返回,返回值是-1.
如果IPC_NOWAIT标志被清除,进程将会挂起以等待一条相应类型的消息到达。