1
我需要在我的Perl代碼中運行外部工具。這個命令在很長一段時間內工作,幾乎不向STDOUT輸出任何東西,但創建一個日誌文件。 我想運行它並行讀取並處理其日誌文件。我如何在Perl中做到這一點?運行外部命令並行處理其日誌文件
在此先感謝。
我需要在我的Perl代碼中運行外部工具。這個命令在很長一段時間內工作,幾乎不向STDOUT輸出任何東西,但創建一個日誌文件。 我想運行它並行讀取並處理其日誌文件。我如何在Perl中做到這一點?運行外部命令並行處理其日誌文件
在此先感謝。
如果您使用類似File::Tail的內容來讀取日誌文件,那麼您可以執行一個簡單的fork
和exec
來運行外部命令。像下面這樣的東西應該工作:
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}
中安裝處理程序,該處理程序將捕獲子進程的終止信號並允許您跳出循環。