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

Why is errno set to 22: mq_open() POSIX


我在尝试使用 C 在 POSIX 中创建 message_queue 时收到错误号 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

上找到

我假设您在 Linux 上使用 mq_open(3),并且 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) on error cases. Notice that POSIX errno.h 规范不会像 EINVAL 那样为错误编号分配数值(这是有意为之的,多个 POSIX 兼容系统可能有不同的编号)。

顺便说一句,您应该始终检查 scanf(3) 的 return 值,在您的情况下:

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

对我来说,是名称中缺少正斜杠“/”导致了 errno 22。