当我尝试减少 POSIX 消息队列中的消息数量时,它的最大值保持为 10。是否可以减少或增加 POSIX 消息队列中的消息数量?
以下代码将消息发送到 POSIX 消息队列。我将最大消息(MQ_MAX_NUM_OF_MESSAGES)设置为 5,但它发送 10 条消息
发送.c
#include <stdio.h>
#include <mqueue.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#define MSGQOBJ_NAME "/myqueue123"
#define MAX_MSG_LEN 70
#define MQ_MESSAGE_MAX_LENGTH 70
#define MQ_MAX_NUM_OF_MESSAGES 5
struct mq_attr attr;
int main(int argc, char *argv[])
{
mqd_t msgq_id;
unsigned int msgprio = 0;
pid_t my_pid = getpid();
char msgcontent[MAX_MSG_LEN];
int create_queue = 0;
char ch; /* for getopt() */
time_t currtime;
attr.mq_flags = 0;
attr.mq_maxmsg = MQ_MAX_NUM_OF_MESSAGES;
attr.mq_msgsize = MQ_MESSAGE_MAX_LENGTH;
attr.mq_curmsgs = 0;
while ((ch = getopt(argc, argv, "qp:")) != -1) {
switch (ch) {
case 'q': /* create the queue */
create_queue = 1;
break;
case 'p': /* specify client id */
msgprio = (unsigned int)strtol(optarg, (char **)NULL, 10);
printf("I (%d) will use priority %d\n", my_pid, msgprio);
break;
default:
printf("Usage: %s [-q] -p msg_prio\n", argv[0]);
exit(1);
}
}
if (msgprio == 0) {
printf("Usage: %s [-q] -p msg_prio\n", argv[0]);
exit(1);
}
if (create_queue) {
msgq_id = mq_open(MSGQOBJ_NAME, O_RDWR | O_CREAT | O_EXCL, S_IRWXU | S_IRWXG, NULL);
} else {
msgq_id = mq_open(MSGQOBJ_NAME, O_RDWR);
}
if (msgq_id == (mqd_t)-1) {
perror("In mq_open()");
exit(1);
}
currtime = time(NULL);
snprintf(msgcontent, MAX_MSG_LEN, "Hello from process %u (at %s).", my_pid, ctime(&currtime));
mq_send(msgq_id, msgcontent, strlen(msgcontent)+1, msgprio);
mq_close(msgq_id);
return 0;
}