5

Can some one tell me how to check if there is any message in message queue. the message queue is implemented in C in linux based operating system. I just want to check if there is any message in the message queue at a particular time.

2
  • How do you implement your message queue? What syscalls are you using (mq_open etc....)? Can you alter the routines handling these queues? Commented Sep 22, 2012 at 11:34
  • 1
    I am just following this guide beej.us/guide/bgipc/output/html/multipage/mq.html I have made my message queue as listed here Commented Sep 22, 2012 at 11:36

1 Answer 1

8

Just checking the amount (if any) of messages is done using the

msgctl() 

function, and examining the msqid_ds structure on return, the msg_qnum in this structure is the amount of messages in the queue. Here is a link with an example: msgctl example, it does more then you want, but after the msgctl() call you just have to check that field in the structure I mentioned above.

#include <sys/msg.h>

main() {
  int msqid = 2;
  int rc;
  struct msqid_ds buf;
  int num_messages;

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

This example should do what you want, and only do what you want.

Sign up to request clarification or add additional context in comments.

2 Comments

I am not able to understand what this functions is doing exactly, but according to me, this code is trying to connect to the message queue, if it is unable to connect it will show error. But how this is will tell if there is a message in message queue or not ?
That is true, I was a little too fast, sorry. I updated the text with only checking IF there actually is a message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.