tee 可以在 c 编程中将 fifo 重定向到 stdout 吗?

can tee redirect a fifo to stdout in c programming?

我想将 fifo 重定向到 stdout 并且 我阅读了文档 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 个参数。 第一个参数应该是 stdin?

来自 tee() 的手册页:

tee() duplicates up to len bytes of data from the pipe referred to by the file descriptor fd_in to the pipe referred to by the file descriptor fd_out.

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

在你给 tee() 的通话中:

tee(fd, STDOUT_FILENO, INT_MAX, SPLICE_F_NONBLOCK);

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

STDIN_FILENOSTDOUT_FILENO 不一定是管道。


如果你想STDOUT_FILENO引用一个管道,你可以运行你的程序在shell的命令行按以下方式:

yourProgram | cat

确保你的 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 是您的程序)适合我。