如果找不到提供的程序,是否可以阻止系统调用cmd.exe?

时间:2011-07-22 07:51:33

标签: windows perl shell system cmd

在Windows上(使用AcitveState perl 5.8 ...),当我使用system从我的perl脚本调用另一个程序时,这样:

my $command="tool.exe"; # or 'C:\fullpath\tool.exe'
my $param = '...';
my $err = system($command, $param);
die("tool not found!") if $err == -1; # never used!
my $errno = $err>>8;
print "Command executed with error code: $errno\n";

我永远无法正确判断系统是否可以找到tool.exe,因为如果找不到(不在路径上,或者指定的完整路径不存在),system显然会自动将命令关闭到cmd.exe,然后cmd.exe将失败,路径未找到(退出代码3)或命令未找到退出代码1!

正如您所看到的,我指定的命令上有 no shell元字符,所以我对shell的内容有点困惑。

另请注意,我已经检查过(使用ProcessExplorer)当tool.exe在路径上时,没有 cmd.exe将被涉及,即perl.exe将是直接的父进程tool.exe。

解决方法:( ??)

如果命令不存在,以下内容至少会给我一个255的退出代码,虽然看起来有点hacky,因为它会将Can't spawn "cmd.exe": No such file or directory at ...打印到STDERR。

my $command="tool.exe"; # or 'C:\fullpath\tool.exe'
my @args = ($command, '...');
my $err = system {$command} @args;
# die("tool not found!") if $err == -1; # never used!
my $errno = $err>>8;
die("tool not found!") if $errno == 255;
print "Command executed with error code: $errno\n";

2 个答案:

答案 0 :(得分:3)

您最好的选择是使用File::Which

use File::Which;
my $exe_path = which('tool.exe');
print "tool.exe not in path" unless $exe_path;

答案 1 :(得分:1)

为什么不使用perl文件存在检查?

if( -e $file_path)  
{  
  #invoke the command  
}