当我在Perl中执行system()调用时,我通常会根据
perldocs检查返回代码.大部分时间$rc!= 0对我来说已经足够了.最近我帮了两个人,在apache下运行.cgi脚本时遇到了系统()调用问题.我指示他们检查$rc
my $rc = system(...);
并将它们链接到system()文档.然后我看得更近了,注意到文档并不是真的在谈论$rc,而是关于$?我感到有点尴尬,出现了以下问题:
是否有区别:
system(...); if ($? == -1) { print "Failed to execute: $!\n"; } elsif ($? & 127) { printf "child died with signal %d,%s coredump\n",($? & 127),($? & 128) ? 'with' : 'without'; } else { printf "child exited with value %d\n",$? >> 8; }
和
my $rc = system(...); if ($rc == -1) { print "Failed to execute: $!\n"; } elsif ($rc & 127) { printf "child died with signal %d,($rc & 127),($rc & 128) ? 'with' : 'without'; } else { printf "child exited with value %d\n",$rc >> 8; }
或者,简而言之,$rc等于$?对于system()?
解决方法
是的,
system
的回报值应等于$?
但是从$?不仅适用于系统调用和$?是一个全局变量,它可能被其他动作所覆盖.从perldoc -v’$?’这些包括:
$CHILD_ERROR
$?
The status returned by the last pipe close,backtick (““”) command,successful call to “wait()” or “waitpid()”,or from the “system()” operator.
保存值立即比较更安全:
my $rc = system('ls myfile.txt'); if ( $rc >> 8 != 0 ) { # do something because ls exited with an error }