【问题标题】:Perl: Tee both merged STDOUT + STDERR and STDERR to separate files without CPAN modulesPerl:将 STDOUT + STDERR 和 STDERR 合并到没有 CPAN 模块的单独文件中
【发布时间】:2014-03-21 13:13:27
【问题描述】:

我在互联网上搜索了不同的解决方案,我所做的最接近的是open 语句中的练习:

use strict;
use warnings;
use Carp;

# Save previous state
my ($old_out, $old_err);

open($old_out, ">&", \*STDOUT) or 
    croak("Cannot save STDOUT: $!\n");
open($old_err, ">&", \*STDERR) or 
    croak("Cannot save STDERR: $!\n");

my ($fh_OUTLOG);
# Make a filehandle for the tee output
open($fh_OUTLOG, "|-", "tee out_err.log") or
    croak("Cannot open filehandle to tee to log file: $!\n");

# Duplicate STDOUT and STDERR to the filehandle
open(STDOUT, ">&", $fh_OUTLOG) or
    croak("Cannot duplicate STDOUT to filehandle: $!\n");

open(STDERR, ">&", $fh_OUTLOG) or
    croak("Cannot duplicate STDERR to filehandle: $!\n");

# Code...


# Restore STDOUT 
open(STDOUT, ">&", $old_out) or
    croak("Cannot restore STDOUT: $!\n");

# Close the filehandle            
close $fh_OUTLOG        
    or croak( ($!) ? "Error closing fh_OUTLOG: $!"
                  : "Exit status $? from tee log.out");

# Restore STDERR   
open(STDERR, ">&", $old_err) or
     croak("Cannot restore STDERR: $!\n");

但是这段代码不会产生带有 STDERR 的日志文件,而且我不知道如何添加它。解决方案的标准是:

  1. Perl v 5.8.3。
  2. 没有 CPAN 模块。
  3. 没有启动脚本的 Bash 额外命令。

我也在考虑为 STDERR 使用一些 teesolutions:

open(STDERR, "| tee log.err");
open(STDERR, ">&", $fh_OUTLOG);

但是使用它会在执行结束时挂起脚本。 (认为​​ tee 子进程仍然存在)。但是如果我最后尝试杀死它,脚本仍然会挂起。

my $pid_std_err = open(STDERR, "| tee log.err") or
     croak("Cannot tee filehandle STDERR to log.err: $!\n");

# Code... 

kill -9, $pid_std_err;

【问题讨论】:

  • 为什么要禁止 CPAN 模块?就好像您实际上并不想编写 Perl 代码一样。 Perl 就是将正确的预构建部分组合在一起。如果您想自己从头开始编写,请使用 C 或其他方式编写它
  • 希望我可以安装 CPAN 模块,但在这个项目中这是不可能的。
  • 如何从 SO 而不是从 CPAN 安装代码?如果我将某些内容从 CPAN 复制到 SO,会发生什么?
  • 如果您可以将 Perl 代码放在服务器上的文件中并运行它,您就可以安装 Perl 模块。它们可以安装在任何地方。

标签: perl logging stdout stderr tee


【解决方案1】:
  1. 创建两个管道并将它们与 STDOUT 和 STDERR 关联。
  2. 创建一个使用 IO::Select 从这两个管道中读取的任务(线程、进程等)。
  3. 任务将从这些管道读取的内容放入适当的文件中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2011-08-20
    • 2017-07-04
    • 2023-01-10
    • 2023-04-06
    • 2012-06-16
    • 2022-12-07
    相关资源
    最近更新 更多