mqueue: message too long

2.8k views Asked by At

When I run the following program i have always the error message "Message too long". Why?

this is the source:

#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);
}   

This is the outupt:

opening mqueue: Success
receiving: Message too long
message: 

/**new edit**/

okok i changed the code for better eliminate some ambiguity

#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;
}   

output

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

There are 2 answers

2
Paul R On

buffer is uninitialised, so strlen(buffer) will return some indeterminate value.

Change:

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

to:

mq_receive(mq, buffer, SIZE, NULL);
0
alk On

You are logging errno without being sure it had been set.

errno only carries a significant value if an error condition was expliclty indicated otherwise, typically by a function returning a specfic value indicating it failed.

You might like to modify your code to something like this:

#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;
}