【问题标题】:Can "tee" command in linux print both the input and the output of a C program?linux中的“tee”命令可以打印C程序的输入和输出吗?
【发布时间】:2020-06-22 01:07:13
【问题描述】:

我有一个简单的 C 程序,它会要求从用户那里获取一个整数,然后它会打印该整数。

#include <stdio.h>
int main() {   
    int number;
    printf("Enter an integer: ");  
    scanf("%d", &number);
    printf("You entered: %d", number);  
    return 0;}

当我使用这个命令时:

gcc program.c -o test
./test | tee text.txt

在终端上运行的程序不会打印输入整数行,而是等待输入,当我提供该输入时,它会打印它并打印到 text.txt 文件夹中。我想按原样运行程序并将终端上运行的所有内容存储到 text.txt 文件夹中,包括输入和输出。有什么可能的方法吗?

【问题讨论】:

  • 这与 C 无关。同样的考虑也适用于用任何语言编写的程序。
  • 还有其他命令可以完成这项工作吗?

标签: linux shell terminal


【解决方案1】:

tee 命令适用于 一个 输入,但您想捕获两个。请注意,您可以使用两个单独的tee 命令,将输入和输出都复制到同一个文件,但最好使用专为您设计的实用程序,例如script

【讨论】:

  • 如何将多个文件描述符通过管道传输到标准输出?
【解决方案2】:

对于基于 Debian 的 Linux,运行 apt install devscripts,然后尝试 annotate-output 实用程序。例如,使用进程替换和根本不存在的文件运行 cat

annotate-output cat <(echo hello) /bin/nosuchfile

...显示其他情况下的输入、输出和标准错误输出,全部发送到标准输出,然后可以通过管道传输到文件:

13:01:03 I: Started cat /dev/fd/63 /bin/nosuchfile
13:01:03 O: hello
13:01:03 E: cat: /bin/nosuchfile: No such file or directory
13:01:03 I: Finished with exitcode 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    相关资源
    最近更新 更多