【问题标题】:Run external command and process its log file in parallel运行外部命令并并行处理其日志文件
【发布时间】:2012-01-26 07:28:28
【问题描述】:

我需要从我的 Perl 代码中运行外部工具。该命令可以运行很长时间,几乎不会向 STDOUT 打印任何内容,但会创建一个日志文件。 我想运行它并并行读取和处理它的日志文件。如何在 Perl 中做到这一点?

提前致谢。

【问题讨论】:

    标签: perl unix ipc fork


    【解决方案1】:

    如果你使用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} 中安装一个处理程序,该处理程序将捕获子进程的终止信号并允许您跳出循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 2022-11-02
      • 2019-03-17
      • 2016-11-07
      相关资源
      最近更新 更多