如何从父级命令并行运行两个子命令?
问题描述:
我需要并行运行两个perl脚本。我怎样才能做到这一点?如何从父级命令并行运行两个子命令?
目前,我有
system("perl command1.pl command2.pl");
命令的文件按顺序执行,直至command1.pl完成command2.pl将无法运行。
我想同时运行这两个命令。
请帮助!
答
`perl command1.pl &`;
`perl command2.pl &`;
..或者使用Perl叉()函数
的perldoc -f叉
..或者使用Perl穿线
的perldoc线程
或者理由T选用一个shell脚本:
#!/bin/sh
./command1.pl &
./command2.pl &
答
取决于命令解释器。在Windows中,您可以使用start
命令启动进程而不用等待。在我记得的大多数* nix命令解释器中,相关记法是在命令末尾添加&符号&
。
答
你可以使用一个piped open的过程中,ALA
use 5.013;
use warnings;
use autodie;
open my $cmd1_fh, '-|', 'dir';
open my $cmd2_fh, '-|', 'cls';
my @child_pids;
for my $cmd ('dir', 'cls') {
defined(my $child_pid = fork()) or die "Couldn't fork: $!";
if ($child_pid == 0) {
exec $cmd;
} else {
push @child_pids, $child_pid;
}
}
for my $pid (@child_pids) {
waitpid($pid, 0);
}
(如果你确实在意输出,然后拨叉然后反拨?)
或者使用线程(我对这个例子并不感到自豪,我甚至还没有写过它。查找使用线程队列::东西更可怕的一个例子)
use threads;
my @threads;
for my $cmd ('dir', 'cls') {
push @threads, threads->create(sub { system @_ }, $cmd);
}
$_->join for @threads;
还有几个模块帮你出这一个,比如Parallel::ForkManager和Win32::Job。
我会解决反向系统()调用。无论如何。 – DVK 2010-12-16 21:10:30
系统调用调用“exec” - 不会被shell解释。它是解释“&”并在后台运行的shell,因此系统无法工作。 – Brad 2010-12-16 21:12:06
不正确:'系统'可能会或可能不会调用shell来解析参数,具体取决于您传递了多少个参数。另外IPC :: System :: Simple也有一些强制调用(或不调用)shell的方法。 – Ether 2010-12-16 22:32:06