在Perl中捕获STDIN的退出状态 [英] Capturing exit status from STDIN in Perl

查看:206
本文介绍了在Perl中捕获STDIN的退出状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用以下命令运行的perl脚本:

I have a perl script that is run with a command like this:

/path/to/binary/executable | /path/to/perl/script.pl

该脚本会对二进制文件的输出执行有用的操作,然后在STDIN用尽时退出(<>返回undef).这一切都很好,除非二进制文件以非零代码退出.从脚本的POV来看,它认为脚本刚刚干净结束,因此它清理并退出,代码为0 .

The script does useful things to the output for the binary file, then exits once STDIN runs out (<> returns undef). This is all well and good, except if the binary exits with a non-zero code. From the script's POV, it thinks the script just ended cleanly, and so it cleans up, and exits, with a code of 0.

有没有办法让perl脚本查看退出代码是什么?理想情况下,我希望这样的工作:

Is there a way for the perl script to see what the exit code was? Ideally, I'd want something like this to work:

# close STDIN, and if there was an error, exit with that same error.
unless (close STDIN) {
   print "error closing STDIN: $! ($?)\n";
   exit $?;
}

但是不幸的是,这似乎不起作用:

But unfortunately, this doesn't seem to work:

$ (date; sleep 3; date; exit 1) | /path/to/perl/script.pl /tmp/test.out
Mon Jun  7 14:43:49 PDT 2010
Mon Jun  7 14:43:52 PDT 2010
$ echo $?
0

有办法让它按我的意思做吗?

Is there a way to have it Do What I Mean?

编辑后添加:

perl脚本实时处理二进制命令的输出,因此将其全部缓冲到文件中不是可行的解决方案.但是,直到脚本结束时才需要知道退出代码.

The perl script is manipulating the output of the binary command in real-time, so buffering it all into a file is not a feasible solution. It doesn't, however, need to know the exit code until the end of the script.

推荐答案

不幸的是,bash似乎放弃了管道上的退出状态.运行"sleep 3 | echo hi"会在睡眠尚未完成之前启动回显,因此绝对没有机会捕获第一个命令的退出状态.

Unfortunately, bash throws away the exit status on a pipe it seems. Running "sleep 3 | echo hi" initiates the echo before the sleep has even completed, so it has absolutely no chance to capture the exit status of the first command.

(理论上)您可以通过将bash命令更改为命令列表来运行此命令-bash会将值保存在$内? (就像Perl一样),但是您必须以某种方式将其传递给Perl脚本,这意味着您的Perl脚本将需要在(例如)命令行上接受上一个程序的退出状态.

You could (in theory) run this by altering the bash command to a list of commands-- bash will save the value within $? (just like Perl), but then you've got to pass it to Perl script somehow, meaning that your Perl script will need to accept the exit status of the previous program on (say) the command line.

或者,您可以重写Perl脚本以运行命令,捕获退出状态,或将整个内容包装在另一个脚本中.

Alternatively, you could just rewrite the Perl script to run the command, and capture the exit status, or wrap the whole thing in yet-another script.

这篇关于在Perl中捕获STDIN的退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆