gpt4 book ai didi

c - 调整 posix 消息队列中的消息数量

转载 作者:太空狗 更新时间:2023-10-29 11:27:33 25 4
gpt4 key购买 nike

当我尝试减少 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;
}

最佳答案

linux manual page对于 posix 消息队列,您可以阅读如何通过 /proc 文件系统调整相关的内核配置。

特别是 /proc/sys/fs/mqueue/msg_max 是您要查找的内容:

This file can be used to view and change the ceiling value for the maximum number of messages in a queue. This value acts as a ceiling on the attr->mq_maxmsg argument given to mq_open(3). The default value for msg_max is 10. The minimum value is 1 (10 in kernels before 2.6.28). The upper limit is HARD_MAX: (131072 / sizeof(void *)) (32768 on Linux/86). This limit is ignored for privileged processes (CAP_SYS_RESOURCE), but the HARD_MAX ceiling is nevertheless imposed.

编辑
mq_open(2) 中所述, mq_getattr(3)mq_send(3)在手册页中,mq_maxmsg 值设置队列可以处理的最大消息数而不阻塞(或者在非阻塞队列的情况下返回 EAGAIN)。如果您 mq_open 一个 mq_maxmsg = 5 的队列并且 /proc 中的内核配置为 10(默认值,AFAIK),那么该队列将接受 5 条消息而不会阻塞。如果您 mq_open 一个 mq_maxmsg = 15 的队列并且 /proc 中的内核配置为 10,则该队列将接受 10 条消息。也就是说:您可以创建一个队列,其中包含的最大消息数小于内核接受的最大消息数,但不能大于。

关于c - 调整 posix 消息队列中的消息数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15728307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com