bugsbunny has asked for the wisdom of the Perl Monks concerning the following question:

hi,
I want to execute traceroute/tracepath and capture its output..that is the easy part.
How can I watch this output and when reach some point i.e. match some string and if it shows up, kill/stop the traceroute and continue my script...
Ability to kill it if it takes too long will be good too..

so, do u have some idea ?

tia

Replies are listed 'Best First'.
Re: watching longstanding processes ?
by moot (Chaplain) on Mar 31, 2005 at 14:54 UTC
    Perhaps something like
    my $some_host = ... my $pid = open TRACE, "traceroute $some_host |"; while (<TRACE>) { if (/some string/) { close TRACE; kill 15, $pid; last; } # other processing here } # rest of script here }
    To handle the timeout you could use alarm, or non-blocking IO on TRACE and count seconds yourself.
Re: watching longstanding processes ?
by tlm (Prior) on Mar 31, 2005 at 15:11 UTC

    Execute traceroute as a read pipe; read its output one line at a time, and close the pipe when the condition is met. To kill the pipe wrap the whole thing in an eval and use an ALRM signal to terminate the process if it takes too long. E.g. (untested)

    open TRACEROUTE, 'traceroute -xyz --whatever|' or die "Pipe failed: $!\n"; { local $SIG{ ALRM } = sub { die "timeout" }; eval { alarm ALARM_INTERVAL; while (<TRACEROUTE>) { # apply your quit test } alarm 0; }; if ( $@ && $@ !~ /timeout/ ) { alarm 0; die $@; } } close TRACEROUTE;

    Update: fixed typo: s/script/pipe/.

    the lowliest monk