mqueue:消息太长了

时间:2013-09-01 10:43:56

标签: c mqueue

当我运行以下程序时,我总是出现错误消息“消息太长”。为什么呢?

这是来源:

#define NAME "/q"
#define SIZE 16

void main()
{
mqd_t mq;
char buffer[SIZE+1];
struct mq_attr attr; 

attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = SIZE;
attr.mq_curmsgs = 0;

mq = mq_open(NAME, O_CREAT | O_RDWR, 0644, &attr);
printf ("opening mqueue: %s\n", strerror(errno));

mq_receive(mq, buffer, strlen(buffer), NULL);
printf ("receiving: %s\n", strerror(errno));

printf ("message: %s\n", buffer);

unlink(NAME);
}   

这是结果:

opening mqueue: Success
receiving: Message too long
message: 

/ ** 新修改 ** /

okok我改变了代码以更好地消除一些歧义

#define NAME "/q"
#define SIZE 1024

int main()
{
  mqd_t mq;
  char buffer[SIZE+1] = {0};
  struct mq_attr attr = {0}; 

  attr.mq_flags = 0;
  attr.mq_maxmsg = 10;
  attr.mq_msgsize = SIZE;
  attr.mq_curmsgs = 0;

  if ((mqd_t) -1 == (mq = mq_open(NAME, O_CREAT | O_RDWR, 0644, &attr)))
    printf("opening mqueue: %s\n", strerror(errno));

  if (-1 == mq_receive(mq, buffer, SIZE+1, NULL))
    printf("receiving: %s\n", strerror(errno));

  printf("message: %s\n", buffer);

  if (-1 == unlink(NAME))
    perror("unlink() failed");

  return 0;
}   

输出

receiving: Message too long
message: 
unlink() failed: No such file or directory

2 个答案:

答案 0 :(得分:1)

您正在记录errno而不确定是否已设置。

errno 带有重要值如果错误条件明确指示,否则通常由返回指示失败的特定值的函数。

您可能希望将代码修改为以下内容:

#define NAME "/q"
#define SIZE 16

int main()
{
  mqd_t mq = ;
  char buffer[SIZE+1] = {0};
  struct mq_attr attr = {0}; 

  attr.mq_flags = 0;
  attr.mq_maxmsg = 10;
  attr.mq_msgsize = SIZE;
  attr.mq_curmsgs = 0;

  if ((mqd_t) -1 == (mq = mq_open(NAME, O_CREAT | O_RDWR, 0644, &attr)))
    printf("opening mqueue: %s\n", strerror(errno));

  if (-1 == mq_receive(mq, buffer, sizeof(buffer), NULL))
    printf("receiving: %s\n", strerror(errno));

  printf("message: %s\n", buffer);

  if (-1 == unlink(NAME))
    perror("unlink() failed"); /* easier varaint of printf ("...: %s\n", strerror(errno));, also prints to stderr, where errors should go. */

  return 0;
}   

答案 1 :(得分:0)

buffer未初始化,因此strlen(buffer)将返回一些不确定的值。

变化:

mq_receive(mq, buffer, strlen(buffer), NULL);

为:

mq_receive(mq, buffer, SIZE, NULL);