Monitoring external process: Exit when STDOUT matches pattern

只谈情不闲聊 提交于 2019-12-12 17:03:57

问题


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;

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?


回答1:


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;



回答2:


You could use awk:

echo hello; sleep 2; echo pattern |awk '{print}/pattern/{exit}' 

This will give you all the lines till pattern occurs, then exit.




回答3:


If the process is to be left running after the match is found, append an & to the command to run it in the background:

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


来源:https://stackoverflow.com/questions/23928271/monitoring-external-process-exit-when-stdout-matches-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!