简体   繁体   English

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

[英]can tee redirect a fifo to stdout in c programming?

I want to redirect a fifo to stdout and I read the doc http://man7.org/linux/man-pages/man2/tee.2.html 我想将一个fifo重定向到stdout并阅读文档http://man7.org/linux/man-pages/man2/tee.2.html

It says tee(int fd_in, int fd_out,...) 它说tee(int fd_in, int fd_out,...)

but when I throw a fifo fd to the 1st arguments, it says invalid error. 但是当我向第一个参数抛出一个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;
}

The console shows: tee:invalid arguments. 控制台显示:tee:无效参数。 The 1st argu should be stdin? 第一个论点应该是stdin?

Make sure your stdout is a pipe. 确保你的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

(where a.out is your program) works for me. a.out是你的程序)适合我。

From tee() 's man pages: 来自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()从文件描述符fd_in引用的管道复制最多len个字节的数据到文件描述符fd_out引用的管道。

So, both file descriptors must refer to pipes. 因此,两个文件描述符都必须引用管道。

In your call to tee() : 在你打电话给tee()

tee(fd, STDOUT_FILENO, INT_MAX, SPLICE_F_NONBLOCK);

fd is a fifo, which is in turn a pipe, but STDOUT_FILENO may not refer to a pipe. fd是一个fifo,它又是一个管道,但STDOUT_FILENO可能不会引用管道。

STDIN_FILENO and STDOUT_FILENO are not necessarily pipes. STDIN_FILENOSTDOUT_FILENO不一定是管道。


If you want STDOUT_FILENO to refer to a pipe, you can run your program at the shell's command line in the following way: 如果希望STDOUT_FILENO引用管道,可以通过以下方式在shell的命令行运行程序:

yourProgram | cat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM