gpt4 book ai didi

c - 为什么errno设置为22 : mq_open() POSIX

转载 作者:行者123 更新时间:2023-12-04 10:28:47 25 4
gpt4 key购买 nike


我在尝试使用 C 在 POSIX 中创建消息队列时收到错误号 22。据我所知,通过与网络上可用的示例代码进行比较,我已经正确设置了参数。

这是一个片段:

    int open_flags;
mqd_t mqfd;
int bytes_per_msg;
struct mq_attr attr;
unsigned int* msgbuff;

printf("from 1 to 400, what is N? : ");
scanf("%d", &n);
bytes_per_msg = (n + 1) * (sizeof(unsigned int));
msgbuff = (unsigned int*)malloc(bytes_per_msg);

open_flags = O_CREAT|O_RDWR;
attr.mq_maxmsg = n;
attr.mq_msgsize = bytes_per_msg;
attr.mq_flags = 0;


mqfd = mq_open("/myqueue", open_flags, 0666, &attr);

if(mqfd == -1){
printf("queue creation failed, ERRNO: %d\n",errno);
}

编辑:我很抱歉没有更清楚。 Errno 22 是无效参数。--错误号的含义可以在errno.h中找到

最佳答案

我假设您使用的是 mq_open(3)在 Linux 上,errno 得到 EINVAL。根据文档,它可能会在以下情况下发生:

name doesn't follow the format in mq_overview(7).

O_CREAT was specified in oflag, and attr was not NULL, but attr->mq_maxmsg or attr->mq_msqsize was invalid. Both of these fields must be greater than zero. In a process that is unprivileged (does not have the CAP_SYS_RESOURCE capability), attr->mq_maxmsg must be less than or equal to the msg_max limit, and attr->mq_msgsize must be less than or equal to the msgsize_max limit. In addition, even in a privileged process, attr->mq_maxmsg cannot exceed the HARD_MAX limit. (See mq_overview(7) for details of these limits.)

所以你也应该阅读mq_overview(7)

顺便说一句,阅读手册总是比在像这里这样的论坛上提问要快。

下次使用perror(3)关于错误案例。请注意 POSIX errno.h规范不会为错误编号分配数值,例如 EINVAL(这是有意为之的,多个 POSIX 兼容系统可能具有不同的编号)。

顺便说一句,你应该经常检查 scanf(3) 的返回值,在你的情况下:

printf("from 1 to 400, what is N? : \n");
n= 0;
if (scanf("%d", &n)<1 || n<=0 || n>400) {
fprintf(stderr, "bad number (n=%d)\n", n);
exit(EXIT_FAILURE);
}

关于c - 为什么errno设置为22 : mq_open() POSIX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29382550/

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