使用嵌套调用和参数进行系统调用

时间:2014-08-08 16:09:26

标签: perl

我正在尝试使用system命令来启动一个带有多个参数的exe,包括启动更多带有参数的exes。

设置如下。

Apple.exe将一切视为一种论据。

Box.exe是一个也带参数的论据。所以现在我们是2层。

这是伪代码,其中引号的数量等于参数层

system(Apple.exe 'Box.exe' "/candy" "/dawn" 'elf.exe' "/fence")

Apple.exe以下的所有内容传递到Apple.exe时,将其分解出来,有些参数可以自行调用。我们最终得到Apple.exe有5个参数,其中2个参数是调用,其中3个是2个调用的参数。

Apple.exe

   Box.exe /candy /dawn

   elf.exe /fence

2 个答案:

答案 0 :(得分:1)

这不是系统调用的方式。当您调用可执行文件时,它会传递一个参数列表。这是一个字符串数组 - 没有嵌套其他数组的概念。这不是Perl特定的限制;它就是系统调用在主流操作系统中的工作方式。

一个建议可能是使用两个参数调用Apple.exe:

system(
   "Apple.exe",
   "Box.exe /candy /dawn",
   "elf.exe /fence",
);

当Apple.exe收到两个参数时,它可以在空格上拆分它们以构建它需要的任何结构。如果参数本身可能包含空格,请选择要拆分的另一个字符:

system(
   "Apple.exe",
   "Box.exe~/candy~/dawn",
   "elf.exe~/fence",
);

或者,您可以将您的参数作为JSON写入文件:

[
  [ "Box.exe", "/candy", "/dawn" ],
  [ "elf.exe", "/fence" ]
]

然后调用Apple.exe,为其提供JSON文件的路径:

system("Apple.exe", "argument-list.json");

当然,无论你做出什么选择,你都需要确保Apple.exe被编程为以你选择传递它们的任何方式接收它的参数。

答案 1 :(得分:0)

如果这是一个基于unix的系统,我会说这些信息是作为一系列shell命令传递的。 apple将被称为如下:

use String::ShellQuote qw( shell_quote );

system(shell_quote('apple', 
   shell_quote('box', '--candy', '--dawn'),
   shell_quote('elf', '--fence'),
));

生成相当于

的东西
apple 'box --candy --dawn' 'elf --fence'

apple看起来像是:

for my $cmd (@ARGV) {
   system($cmd);   # aka system('sh', '-c', $cmd);
}

但是你似乎在使用Windows,而Windows中的命令行处理有点脆弱。你可以试试

use Win32::ShellQuote qw( quote_cmd );

system(quote_cmd('apple', 
   quote_cmd('box', '/candy', '/dawn'),
   quote_cmd('elf', '/fence'),
));

产生一个丑陋的混乱,应该等同于

apple "box /candy /dawn" "elf /fence"

apple仍然如下:

for my $cmd (@ARGV) {
   system($cmd);   # aka system('cmd', '/x', '/c', $cmd);
}
相关问题