如果找不到提供的程序,我可以阻止系统调用 cmd.exe 吗?
在 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 将失败,并显示 path-not-found(退出代码 3)或 command-not-found退出代码 1!
正如您所看到的,我指定的命令中没有 shell 元字符,所以我有点困惑 shell 是如何进入那里的。
另请注意,我(使用 ProcessExplorer)检查过,当 tool.exe 位于路径上时,不会涉及 cmd.exe,即 perl.exe 将是 tool.exe 的直接父进程。
解决方法:(??)
如果命令不存在,以下至少会给我一个 255
退出代码,尽管它看起来有点 hacky,因为它会打印 Can不生成“cmd.exe”:在 ...
处没有此类文件或目录到 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";
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, i.e. 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";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的选择是使用
File::Which
Your best bet will be to use
File::Which
为什么不使用 perl 文件存在检查?
Why don'tyou use the perl file exist check?