首页 文章

将父进程的STDERR重定向到子进程的文件句柄

提问于
浏览
4

我需要从Perl脚本调用外部日志记录进程,该脚本将传递给它的数据并将其写入网络服务 . 这很容易做到 . 但是,我还有一个额外的要求,即从父进程对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)上 .

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

1 回答

  • 3

    只需重新分配 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;
    

相关问题