2011-12-22 13 views
1

私のPerlコード内から外部ツールを実行する必要があります。このコマンドはかなり長い間働き、STDOUTにはほとんど何も出力しませんが、ログファイルを作成します。 私はそれを実行し、そのログファイルを並列に読み込んで処理したいと思います。 Perlでどうすればいいですか?外部コマンドを実行し、そのログファイルを並列に処理します

ありがとうございます。

答えて

2

File::Tailのようなものを使用してログファイルを読み取る場合は、forkexecを使用して外部コマンドを実行できます。以下のようなものが動作するはずです:

use strict; 
use warnings; 

use File::Tail; 

my $pid = fork; 

if ($pid) { 
    # in the parent process; open the log file and wait for input 
    my $tail = File::Tail->new('/path/to/logfile.log'); 
    while(my $line = $tail->read) { 
     # do stuff with $line here 
     last if $line eq 'done running'; # we need something to escape the loop 
              # or it will wait forever for input. 
    } 
} else { 
    # in the child process, run the external command 
    exec 'some_command', 'arg1', 'arg2'; 
} 

# wait for child process to exit and clean it up 
my $exit_pid = wait; 

子プロセスの実行に問題がある場合は、終了戻りコードが特殊変数$?になります。詳細については、waitのドキュメントを参照してください。

また、ロギング出力がファイルのテールリングをいつ停止するかの手がかりを与えない場合は、$SIG{CHLD}にハンドラをインストールして、子プロセスの終了信号を捕捉してループから抜け出すことができます。

関連する問題