繁体   English   中英

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

[英]Can I prevent system from invoking cmd.exe if the supplied program is not found?

在 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,然后将失败并出现 路径未找到(退出代码 3)或命令未找到 退出代码 1!

如您所见,我指定的命令中没有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";

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM