在Perl中,如何阻止一堆系统调用才能完成? [英] In Perl, how can I block for a bunch of system calls to finish?
本文介绍了在Perl中,如何阻止一堆系统调用才能完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一堆我想并行运行的系统调用:
I'm doing a bunch of system calls that I want to run in parallel:
system(" sleep 5 && echo step 1 done &");
system(" sleep 3 && echo step 2 done &");
system(" sleep 7 && echo step 3 done &");
// block here
如何阻止程序流,直到所有系统调用完成?
How can I block the program flow until all the system calls are finished?
推荐答案
最简单的方法可能是为每个系统调用fork
一个新的子进程,然后等待它们完成.这是一个简化的示例:
The easiest way to do this is probably to fork
a new child process for each system call, and then wait for them to finish. Here's a simplified example:
my @commands = ( "sleep 5 && echo step 1 done",
"sleep 3 && echo step 2 done",
"sleep 7 && echo step 3 done" );
my @pids;
foreach my $cmd( @commands ) {
my $pid = fork;
if ( $pid ) {
# parent process
push @pids, $pid;
next;
}
# now we're in the child
system( $cmd );
exit; # terminate the child
}
wait for @pids; # wait for each child to terminate
print "all done.\n";
这篇关于在Perl中,如何阻止一堆系统调用才能完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文