【问题标题】:Require exit status !=0 when script inside system command doesn't go well [duplicate]当系统命令中的脚本运行不顺利时,需要退出状态!=0 [重复]
【发布时间】:2021-10-07 12:33:50
【问题描述】:

inter.pl 的代码是:

use strict;
use warnings;

my $var1=`cat /gra/def/ment/ckfile.txt`;  #ckfile.txt doesn't exist
print "Hello World";
exit 0;

ext.pl 的代码

my $rc = system ("perl inter.pl");
print "$rc is rc\n";

在这里,当我运行“perl ext.pl”时,$rc 将变为 0。

虽然 inter.pl (/gra/def/ment/ckfile.txt) 中的文件不存在,但我得到的 $rc 为 0。

在同样的情况下,我希望 $rc 为 != 0(在一种情况下,这应该是一个错误,因为文件 ckfile.txt 不存在)。

注意: 我不能在 inter.pl 中做任何修改

如何实现?

提前致谢。

【问题讨论】:

  • 很难不修改inter.pl。错误在子进程(运行cat …的进程),错误代码在子进程完成后在$?中可用,然后脚本继续执行,包括最后一条exit 0指令。因此,无论ckfile.txt 是否存在,ext.pl 总是会看到inter.pl 的“干净”运行。
  • 如果你不能修改 inter.pl,你应该在关于这个话题的第一个问题中提到。

标签: perl system backticks exitstatus


【解决方案1】:

如果您希望程序具有非零退出状态,则需要替换(无用的)exit 0;

my $var1=`cat /gra/def/ment/ckfile.txt`;
exit 1 if $?;

my $var1=`cat /gra/def/ment/ckfile.txt`;
die("Can't spawn child: $!\n") if $? == -1;
die("Child killed by signal ".( $? & 0x7F )."\n") if $? & 0x7F;
die("Child exited with error ".( $? >> 8 )."\n") if $? >> 8;

【讨论】:

  • 我会使用POSIX functions${^CHILD_ERROR_NATIVE} 来检查退出状态,而不是幻数和位移。 (另外,&& 不应该是 & 吗?)
  • @ikegami 这个脚本只是一个示例。实际的脚本非常大且有意义,出口是一个同样重要的功能。因此,无法删除出口 0。而且,您提到的第二种方法是不可行的,因为在 2000 行的脚本代码中,不可能总是添加此检查。
猜你喜欢
  • 1970-01-01
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 2021-01-10
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多