0

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

这是来源:

#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: 

/ **新编辑** /

好的,我更改了代码以更好地消除一些歧义

#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
4

2 回答 2

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;
}   
于 2013-09-01T11:30:22.797 回答
0

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

改变:

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

至:

mq_receive(mq, buffer, SIZE, NULL);
于 2013-09-01T10:50:24.010 回答