运行外部命令并并行处理其日志文件

发布于 2024-12-22 07:32:04 字数 121 浏览 2 评论 0原文

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

提前致谢。

I need to run external tool from within my Perl code. This command works for a pretty long time, prints almost nothing to STDOUT but creates a log file.
I would like to run it and in parallel read and process its log file. How can I do it in Perl?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2024-12-29 07:32:04

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

If you use something like File::Tail to read the log file, then you can do a simple fork and exec to run the external command. Something like the following should work:

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;

If there are problems running the child process, the exit return code will be in the special variable $?; see the documentation for wait for more information.

Also, if the logging output does not provide a clue for when to stop tailing the file, you can install a handler in $SIG{CHLD} which will catch the child process's termination signal and allow you to break out of the loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文