【问题标题】:Redirect STDERR of parent process to file handle of child process将父进程的STDERR重定向到子进程的文件句柄
【发布时间】:2014-09-15 06:18:36
【问题描述】:

我需要从 Perl 脚本中调用一个外部日志记录进程,该脚本获取传递给它的数据并将其写入网络服务。这很容易做到。但是,我还有一个额外的要求,即从 parent 进程对 STDERR 的任何写入都将重定向到外部进程。

我尝试做的是打开外部进程写入管道的文件句柄,然后将 STDERR 重定向到文件句柄。这是我的测试脚本,不幸的是它还不能工作。

#!/usr/bin/perl

use strict;
use warnings;

# open write filehandle to external process
open my $fh, '|-', 'pipefile_http',
  or die "Couldn't open logfile: $!\n";

# redirect STDERR from parent process to same write filehandle to child process
my $fileno = fileno($fh);
open STDERR, ">&$fileno" or die "Couldn't switch STDERR to fileno $fileno: $!\n";

print $fh "1. print to file handle\n";

print STDERR "2. print to STDERR\n";

print "3. print to STDOUT\n";

close $fh;

exit 0;

当我运行此脚本时,它成功地将对 STDERR 的打印调用重定向到外部日志记录进程,但对 $fh 的打印调用不起作用(消息消失)。此外,脚本在成功将消息 #3 打印到 STDOUT 后会无限期挂起。当我使用 strace 运行脚本时,我可以看到脚本挂在 waitpid() 调用(外部进程的 pid)上。

关于如何做到这一点的任何建议?

【问题讨论】:

    标签: perl


    【解决方案1】:

    只需重新分配STDERR

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    # open write filehandle to external process
    open my $fh, '|-', 'pipefile_http',
        or die "Couldn't open logfile: $!\n";
    
    # reassign STDERR
    *STDERR = $fh;
    
    print $fh "1. print to file handle\n";
    print STDERR "2. print to STDERR\n";
    print "3. print to STDOUT\n";
    
    close $fh;
    
    exit 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-14
      • 2020-03-11
      • 1970-01-01
      • 2012-07-04
      • 2017-06-25
      • 1970-01-01
      • 2015-08-18
      • 2021-10-01
      相关资源
      最近更新 更多