【问题标题】:F_GETPIPE_SZ returns -1 in CF_GETPIPE_SZ 在 C 中返回 -1
【发布时间】:2016-06-18 02:48:48
【问题描述】:

为什么 F_GETPIPE_SZ 会返回 -1?这听起来像是一个错误,但我找不到任何关于它是什么错误的提及,或者更重要的是,我应该做什么才能不得到错误。

我在 Raspberry Pi 上运行 Raspbian,物有所值。我还没有在我的桌面 Debian 上尝试过代码。据我所知,我正在遵循教科书 F_GETPIPE_SZ 示例。我错过了什么吗?

#define _GNU_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char **argv)
{
  int fd, pipesize;
  fd = mkfifo("/tmp/audio-fifo",0666);
  //  fcntl(fd, F_SETPIPE_SZ, 4096);
  pipesize = fcntl(fd, F_GETPIPE_SZ);
  printf("Pipe size: %d\n", pipesize);
  return 0;
}

【问题讨论】:

  • mkfifo 成功返回 0,失败返回 -1。而fnctl 期望第一个参数是文件描述符。
  • 换句话说,mkfifo ...; fd = open("/tmp/audio-fifo", ...)
  • 尝试在fcntl() 之后直接检查errno(使用#include &lt;errno.h&gt;)。但是错误值大概是EINVAL。假设mkfifo() 成功,您尝试获取文件描述符0 的管道大小。 mkfifo() 为 fifo 创建文件系统条目,它不会打开 fifo 的文件描述符。
  • 谢谢大家,我现在明白为什么错了。所以我只是在 mkfifo 中使用相同的路径字符串并打开?

标签: pipe c fifo


【解决方案1】:

mkfifo 只会为您创建特殊文件。它会在成功时返回0,如果发生错误则返回errno

使用mkfifo 创建管道后,您必须使用open 打开该文件。之后,您将有一个有效的文件描述符来传递fnctl(只要这些函数都没有返回错误!)。

所以基本上你缺少的是open 命令。

【讨论】:

    【解决方案2】:

    按照 Nidhoegger 的回答,这里有一个完整的例子

    错误处理留给读者作为练习(失败的调用将在很大程度上返回-1,应在mkfifo 之后和使用fd 之前检查)

    #define _GNU_SOURCE
    #include <stdio.h>
    #include <fcntl.h>
    #include <sys/stat.h>
    #include <unistd.h>  // not required
    
    #define PATH "/tmp/audio-fifo"
    
    int main(int argc, char **argv)
    {
        int fd;
    
        // create a fifo at PATH
        mkfifo(PATH, 0644);
        fd = open(PATH, O_RDWR);
        printf("Pipe size: %d\n", fcntl(fd, F_GETPIPE_SZ));
    
        // resize the pipe with fcntl
        fcntl(fd, F_SETPIPE_SZ, 4096);
        printf("Pipe size: %d\n", fcntl(fd, F_GETPIPE_SZ));
    
        return 0;
    }
    
    % gcc test.c && ./a.out
    Pipe size: 65536
    Pipe size: 4096
    

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 2011-12-28
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      相关资源
      最近更新 更多