简体   繁体   中英

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

On Windows (with AcitveState perl 5.8...), when I use system to invoke another program from my perl script like this:

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";

I never can properly determine whether tool.exe can be found by system, because if it isn't found (isn't on the path, or the full path specified doesn't exist) system will apparently automatically pass the command off to cmd.exe, which then will fail with either path-not-found (exit code 3) or with command-not-found exit code 1!

As you can see, there are no shell metacharacters on the command I specify, so I'm a bit confused how the shell gets in there.

Also note that I have checked (with ProcessExplorer) that when the tool.exe is on the path, no cmd.exe will be involved, ie perl.exe will be the direct parent process of tool.exe.

Workaround: (??)

The following will at least get me an exit code of 255 if the command doesn't exist, although it appears to be a bit hacky, as it will print Can't spawn "cmd.exe": No such file or directory at... to 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";

Your best bet will be to use File::Which

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

Why don'tyou use the perl file exist check?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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