如何删除或清除c中POSIX消息队列中的所有消息?

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

我想从 POSIX 消息队列中删除所有消息。我在互联网上搜索,但没有找到任何方法,而是找到了删除消息队列本身的方法,但这不是我的情况,我实际上想从消息队列中清除所有待处理的消息。

我在阅读手册页时发现 mq_setattr API 用于控制消息队列的参数。我只是想知道如果我使用 mq_setattrmq_curmsgs 的值设置为 0,它会从队列中清除未决消息吗?

在这方面的任何帮助将不胜感激

清除消息队列的一种方法是mq_receive所有消息但不处理它们。


man mq_setattr:

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

以下伪代码对我有用。

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