http://www.perlmonks.org?node_id=412041


in reply to question about running a system and a perl function background

You want to be able to:

  1. Run several external commands concurrently.
  2. Check the output from those commands for some keyword(s).
  3. (Optionally?) Have the outputs end up in files. (or is this just so you can search the output later?).
  4. Have the script that starts the concurrent processes know:
    1. when the tasks completed.
    2. Whether the output contained the keyword(s).

threads and the 'piped' version of open (see perlopentut) makes this kind of concurrency easy.

#! perl -slw use strict; use threads qw[ async ]; use threads::shared; sub runAndCheck { my( $cmd, $lookFor, $file, $checkRef, $doneRef ) = @_; open OUT, '>', $file or die "$file : $!"; open CMD, "$cmd |" or die "$cmd : $!"; while ( <CMD> ) { $$checkRef = 1 if $_ =~ $lookFor; print OUT; } close CMD; close OUT; $$doneRef = 1; } my @cmds = map{ "dir $_" } qw[ c:\ P:\test r:\ d:\ ]; my @checks : shared = ( 0 ) x @cmds; my @dones : shared = ( 0 ) x @cmds; my $lookFor = 'junk.htm'; async{ runAndCheck( $cmds[ $_ ], $lookFor, "test$_.out", \$checks[ $_ ], \$dones[ $_ ] ); }->detach for 0 .. $#cmds; while( grep( $_, @dones ) < @cmds ) { sleep 1; for ( 0 .. $#cmds ) { if( $dones[ $_ ] == 1 ) { printf "'$cmds[ $_ ]' completed; '$lookFor' "; print $checks[ $_ ] ? 'was found' : 'was not found'; $dones[ $_ ] = 2; } } } __END__ P:\test>412014 'dir c:\' completed; 'junk.htm' was not found 'dir P:\test' completed; 'junk.htm' was found 'dir r:\' completed; 'junk.htm' was not found 'dir d:\' completed; 'junk.htm' was not found P:\test>412014 'dir c:\' completed; 'junk.htm' was not found 'dir r:\' completed; 'junk.htm' was not found 'dir d:\' completed; 'junk.htm' was not found 'dir P:\/s' completed; 'junk.htm' was found

Examine what is said, not who speaks.
"But you should never overestimate the ingenuity of the sceptics to come up with a counter-argument." -Myles Allen
"Think for yourself!" - Abigail        "Time is a poor substitute for thought"--theorbtwo         "Efficiency is intelligent laziness." -David Dunham
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon