【问题标题】:can tee redirect a fifo to stdout in c programming?可以在 c 编程中将 fifo 重定向到标准输出吗?
【发布时间】:2017-08-18 08:58:33
【问题描述】:

我想将一个先进先出重定向到标准输出和 我读了文档http://man7.org/linux/man-pages/man2/tee.2.html

上面写着tee(int fd_in, int fd_out,...)

但是当我向第一个参数抛出一个 fifo fd 时,它会显示无效错误。

#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
int main() {
    int num = 0, fd;
    char fifo[] = "/tmp/tmpfifo";

    fd = open(fifo, O_RDONLY, 0644);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }
    num = tee(fd, STDOUT_FILENO, INT_MAX, SPLICE_F_NONBLOCK);
    if (num < 0) {
        perror("tee");
        exit(EXIT_FAILURE);
    }
    fprintf(stderr,"%d\n", num);
    return 0;
}

控制台显示:tee:invalid arguments。 第一个参数应该是标准输入?

【问题讨论】:

  • 我想你想要dup2 函数。
  • 顺便问一下,您确定传递给open 的标志吗?不应该只有O_RDONLYO_WRONLY吗?您的程序是否应该与自身通信?你是如何创建 FIFO 的?
  • 如果我仍然使用 tee() 系统调用,这是否有效?
  • 通过您的编辑,目的是自动将您从 FIFO 中读取的所有内容通过管道传输到 stdout?您要解决的实际问题是什么?
  • 您不应该为读写打开一个fifo,您必须将调用分开......tee旨在与fifos一起使用,来自文档EINVAL fd_in or fd_out does not refer to a pipe; or fd_in and fd_out refer to the same pipe.。标准输出是先进先出吗?

标签: c linux pipe fifo


【解决方案1】:

确保您的 stdout 是管道。

rm -f /tmp/tmpfifo
mkfifo /tmp/tmpfifo
echo hello world > /tmp/tmpfifo & 
./a.out | cat #ensure that the program's stdout is a pipe

a.out 是你的程序)对我有用。

【讨论】:

  • 它有效。我以为 STDOUT_FILENO 最初会在控制台上打印。
【解决方案2】:

来自tee() 的手册页:

tee() 从引用的管道复制最多 len 个字节的数据 文件描述符 fd_in 指向文件引用的管道 描述符 fd_out。

所以,两个文件描述符都必须引用管道。

在您致电tee()

tee(fd, STDOUT_FILENO, INT_MAX, SPLICE_F_NONBLOCK);

fd 是一个fifo,它又是一个管道,但STDOUT_FILENO 可能不是一个管道。

STDIN_FILENOSTDOUT_FILENO 不一定是管道。


如果您希望STDOUT_FILENO 引用管道,您可以通过以下方式在 shell 的命令行中运行您的程序:

yourProgram | cat

【讨论】:

  • fifo 不是管道吗?
  • @code_worker 但STDOUT_FILENO 不一定是管道。
  • 我知道。但是我打开一个fifo,fifo是一个管道。所以我认为将fifo放在第一个argu应该是正确的,对吧?
  • @code_worker 你可以以./myProgram | cat 执行你的程序,然后STOUT_FILENO 指的是一个管道。
  • 实际上是shell创建了管道,你的程序只是继承(作为一个子进程)一个对应于该管道的文件描述符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
  • 1970-01-01
相关资源
最近更新 更多