简体   繁体   English

在Perl中,如何阻止一堆系统调用完成?

[英]In Perl, how can I block for a bunch of system calls to finish?

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? 在完成所有系统调用之前,如何阻止程序流程?

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. 最简单的方法是为每个系统调用fork一个新的子进程,然后等待它们完成。 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";

Fork a child process to perform each job, and in the parent, wait for those processes to finish before exiting. 分叉子进程以执行每个作业,并在父进程中等待这些进程在退出之前完成。

See perldoc perlfork , perldoc -f fork and perldoc -f waitpid . 请参阅perldoc perlforkperldoc -f forkperldoc -f waitpid

(The exact code for this is left as an exercise for the reader -- everyone should have to write this from scratch at least once, to understand the details involved. There are lots of examples on this site as well.) (确切的代码留给读者练习 - 每个人都应该至少从头开始写一次,以了解所涉及的细节。这个网站上也有很多例子。)

如何从不同的线程运行每个系统调用并加入线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM