簡體   English   中英

可以在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:無效參數。 第一個論點應該是stdin?

確保你的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是你的程序)適合我。

來自tee()的手冊頁:

tee()從文件描述符fd_in引用的管道復制最多len個字節的數據到文件描述符fd_out引用的管道。

因此,兩個文件描述符都必須引用管道。

在你打電話給tee()

tee(fd, STDOUT_FILENO, INT_MAX, SPLICE_F_NONBLOCK);

fd是一個fifo,它又是一個管道,但STDOUT_FILENO可能不會引用管道。

STDIN_FILENOSTDOUT_FILENO不一定是管道。


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

yourProgram | cat

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM