LoginSignup
6
6

More than 5 years have passed since last update.

perlでforkを使う

Last updated at Posted at 2014-06-02

perlでforkを使うのに「Parallel::ForkManager」が便利そう。

並列処理のプロセスの分岐数などが楽に制御できるので、CPUを複数使う処理やクローラーなどで便利な雰囲気。

★インストール

shell
# yum install --enablerepo=rpmforge perl-Parallel-ForkManager.noarch

「rpmforge」を入れてなければリポジトリ追加。

★使い方(perl Docから)

test.pl
#!/usr/bin/perl

use Parallel::ForkManager;

$pm = new Parallel::ForkManager(2);

while ($cnt < 10) {
    $cnt++;
    # Forks and returns the pid for the child:
    my $pid = $pm->start and next;

    system("./test2.pl");

    $pm->finish; # Terminates the child process
}
$pm->wait_all_children;
test2.pl
#!/usr/bin/perl

print "aaaa\n";
sleep 2;
print "bbbb\n";

「$pm->wait_all_children;」を入れないと、最後のプロセスを待たずにプログラムが終了してしまいます。
上記例ですと9、10個目の子プロセスを開始した段階で親プロセスが終了します。

・参考
 http://perldoc.jp/docs/modules/Parallel-ForkManager-0.7.5/ForkManager.pod

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6