'How to delete or clear all the messages from the POSIX message queue in c?

I want to delete all the messages from the POSIX message queue. I searched on the internet but I didn't find any way to do it instead I found the way to delete the message queue itself but that's not my case I actually want to clear all the pending messages from the message queue.

I was reading the man page in which I found mq_setattr API which is used to control the parameter for the message queue. I was just wondering if I set the value of mq_curmsgs to 0 by using mq_setattr, would it clear the pending messages from the queue?

Any help in this regard will be appreciated



Solution 1:[1]

One way to clear a message queue is to mq_receive all messages but not process them.


man mq_setattr:

The only attribute that can be modified is the setting of the O_NONBLOCK flag in mq_flags.

Solution 2:[2]

The following pseudocode worked for me.

 struct mq_attr attr;
 mq = mq_open( .... ); // Create message queue.
 
 if( mq_getattr(mq, &attr) == 0 ){
    while(attr.mq_curmsgs) {
      printf("Clearing pending message # %d from the queue", (int)attr.mq_curmsgs);
      mq_receive(mq, .....);
      attr.mq_curmsg--;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maxim Egorushkin
Solution 2 Preetham Rangaswamy