0

In linux, what should be the output of message queue, when message queue is empty?

First I have send 2 message in one message queue then I have received 2 message from message queue. Now again I am trying to receive message from message queue then I am getting garbage value. Then tell me why I am getting this garbage value ?

Receive.c

#include <stdio.h>
#include <sys/msg.h>
#include <error.h>
#include <strings.h>

int main() 
{
   int msqid;

   struct message 
   {
      long type;
      char text[20];
   } msg;

   struct msqid_ds buf;

   int msgtype = 3;
   int num_messages;
   int count;
   int key = 1234;

   msqid = msgget(key,0644);

   count = msgctl(msqid,IPC_STAT,&buf);
   num_messages = buf.msg_qnum;

   printf("Number of messages = %d\n",num_messages);

   if (msgrcv(msqid, (void *) &msg, sizeof(msg.text), msgtype, MSG_NOERROR| IPC_NOWAIT)==-1);
   {  
    perror("msgrcv");           
   }

   /*  if(num_messages==0)
       {
              printf("Queue is empty\n");
       }
       else
       {  */   
           printf("%s \n", msg.text);
    // }

       return 0;
 }

Send.c

#include <string.h>
#include <sys/msg.h> 
#include <stdio.h>
int main() 
{
    struct message 
    {
        long type;
        char text[20];
    } msg;

    int msqid;
    int key = 1234;
    msqid = msgget(key,IPC_CREAT|0644);

    msg.type = 3;
    strcpy(msg.text, "This is message 1");
    msgsnd(msqid, (void *) &msg, sizeof(msg.text), IPC_NOWAIT);
    strcpy(msg.text, "This is message 2");
    msgsnd(msqid, (void *) &msg, sizeof(msg.text), IPC_NOWAIT);

    printf("2 messages are succesfully send \n");
    return 0; 
}
Kara
  • 6,115
  • 16
  • 50
  • 57

1 Answers1

1

You need to check the return value of msgrcv (you do that already) and errno. From msgrcv documentation:

IPC_NOWAIT Return immediately if no message of the requested type is in the queue. The system call fails with errno set to ENOMSG.

If you ignore the failure and try to read msg, its values are going to be undetermined because it was not initialized. E.g.:

if(msgrcv(msqid, &msg, sizeof(msg.text), msgtype, MSG_NOERROR | IPC_NOWAIT))
{
    if(ENOMSG == errno)
        fprintf(stderr, "No messages found\n");
    else
        perror("msgrcv");
}
else {
    // Successfully received a message into msg.
}

(Note that in the original code you have a semi-colon after if, which is probably not what you want).

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271