监视外部进程:当STDOUT匹配模式时退出 [英] Monitoring external process: Exit when STDOUT matches pattern

查看:141
本文介绍了监视外部进程:当STDOUT匹配模式时退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行系统命令并等待输出匹配特定模式,例如:

I'm running a system command and waiting for output matching a specific pattern, e.g:

open(my $fh, '-|', 'echo line 1; sleep 20; echo line 2');
while (<$fh>) {
    print && last if /1/;
}
close $fh;

这将打印第1行并离开循环但在外部命令完成之前不会退出。

This will print line 1 and leave the loop but won't exit until the external command has completed.

如何在匹配所需输出后立即允许脚本退出?

How can I allow the script to exit immediately after matching the required output?

推荐答案

您可以将 TERM 信号发送到PID,然后关闭文件句柄而无需等待,

You can send TERM signal to the PID and then close file handle without waiting,

my $pid = open(my $fh, '-|', 'echo line 1;sleep 5; echo line 2') or die $!;
while (<$fh>) {
    print && last if /1/;
}
kill TERM => $pid;
close $fh;

这篇关于监视外部进程:当STDOUT匹配模式时退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆