簡體   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