如何使Perl等待在后台使用system()启动的子进程? [英] How can I make Perl wait for child processes started in the background with system()?
本文介绍了如何使Perl等待在后台使用system()启动的子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了简化起见,我有一些Perl代码可以执行多个参数的shell脚本,我只是假设我有如下代码:
I have some Perl code that executes a shell script for multiple parameters, to simplify, I'll just assume that I have code that looks like this:
for $p (@a){
system("/path/to/file.sh $p&");
}
我想在那之后做更多的事情,但是我可以无法找到一种方法来等待所有子进程完成后再继续。
I'd like to do some more things after that, but I can't find a way to wait for all the child processes to finish before continuing.
将代码转换为使用fork()会很困难。
Converting the code to use fork() would be difficult. Isn't there an easier way?
推荐答案
使用fork / exec / wait还不错:
Using fork/exec/wait isn't so bad:
my @a = (1, 2, 3);
for my $p (@a) {
my $pid = fork();
if ($pid == -1) {
die;
} elsif ($pid == 0) {
exec '/bin/sleep', $p or die;
}
}
while (wait() != -1) {}
print "Done\n";
这篇关于如何使Perl等待在后台使用system()启动的子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文