Chr*_*ris 3 c posix message-queue
我在尝试使用 C 在 POSIX 中创建 message_queue 时收到 errno 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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:我很抱歉没有更清楚。错误 22 是无效参数。--错误编号的含义可以在errno.h中找到
我假设您在 Linux上使用mq_open(3),并且errno正在获取EINVAL. 根据文档,它可能发生在:
名称不遵循 mq_overview(7) 中的格式。
或者
在oflag中指定了O_CREAT,attr不为NULL,但attr->mq_maxmsg或attr->mq_msqsize无效。这两个字段都必须大于零。在非特权进程(没有CAP_SYS_RESOURCE 能力)中,attr->mq_maxmsg 必须小于或等于msg_max 限制,并且attr->mq_msgsize 必须小于或等于msgsize_max 限制。此外,即使在特权进程中,attr->mq_maxmsg 也不能超过 HARD_MAX 限制。(有关这些限制的详细信息,请参阅 mq_overview(7)。)
所以你也应该阅读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);
}
Run Code Online (Sandbox Code Playgroud)