perl – 将父进程的STDERR重定向到子进程的文件句柄
发布时间:2020-12-16 06:15:43 所属栏目:大数据 来源:网络整理
导读:我需要从Perl脚本调用外部日志记录进程,该脚本将传递给它的数据并将其写入网络服务.这很容易做到.但是,我有额外的要求,即从父进程对STDERR的任何写入都会被重定向到外部进程. 我尝试做的是打开外部进程的写管道的文件句柄,然后将STDERR重定向到文件句柄.这是
我需要从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 handlen"; print STDERR "2. print to STDERRn"; print "3. print to STDOUTn"; close $fh; exit 0; 当我运行此脚本时,它成功地将对STDERR的打印调用重定向到外部日志记录过程,但是对$fh的打印调用不起作用(消息消失).此外,脚本在成功将消息#3打印到STDOUT后无限期挂起.当我用strace运行脚本时,我可以看到脚本挂在waitpid()调用(外部进程的pid)上. 有关如何做到这一点的任何建议? 解决方法
只需重新分配STDERR:
#!/usr/bin/perl use strict; use warnings; # open write filehandle to external process open my $fh,or die "Couldn't open logfile: $!n"; # reassign STDERR *STDERR = $fh; print $fh "1. print to file handlen"; print STDERR "2. print to STDERRn"; print "3. print to STDOUTn"; close $fh; exit 0; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |