【问题标题】:Why is errno set to 22: mq_open() POSIX为什么 errno 设置为 22:mq_open() POSIX
【发布时间】:2015-06-05 14:43:33
【问题描述】:

我在尝试使用 C 在 POSIX 中创建 message_queue 时收到 errno 22。 据我所知,通过与网络上提供的示例代码进行比较,我已经正确设置了参数。

这是一个sn-p:

    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

【问题讨论】:

  • perror()检查errno所指的内容。
  • 您可以在 errno.h 上查找 errno 的含义。使用 perror 得出相同的结论:错误 22:无效参数> 我试图找出我的参数无效的内容。我不记得我在哪里找到没有错误的 errno @WilliamPursell
  • @Chris:我们无法在您的机器上查看 errno.h — POSIX 中没有任何内容说“errno 22 应为 EINVAL — 无效参数”。因此,您必须为我们翻译;您可以访问您的机器并且可以这样做。
  • 所以 errno.h 可能因机器而异?这也是我没有意识到的。我发现的每个显示 errno.h 内容的网页都是一样的。
  • errno.h 在不同的操作系统上可能不同。 SunOS4/Sparc 可能与 Linux/x86-64 和 IIRC 不同,Linux/ARM 和 Linux/x86-64 也不同

标签: c posix message-queue


【解决方案1】:

我假设你在 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);
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多