Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Need advice on how to fork with intercommunication

by gryphon (Abbot)
on Aug 05, 2007 at 14:50 UTC ( #630721=note: print w/ replies, xml ) Need Help??


in reply to Need advice on how to fork with intercommunication

Greetings ewhitt,

Forking is nice, but when I need data back to the parent, I like using threads instead. The communication between source and thread is simple, only once at the end, but it usually does what I need, and it's pretty intuative.

If you need communication before the end of the thread, you can set that up with shared data structures with threads::shared.

#!/usr/bin/perl use strict; use warnings; use threads; use IO::File; use Net::SSH 'sshopen2'; use DBI; # username@hostname connect strings my @servers = qw( gryphon@hornet gryphon@kursk gryphon@garfield ); # startup a thread for each server my @threads = map { threads->new( sub { my ($server) = $_[0]; my ( $reader, $writer ) = ( IO::File->new(), IO::File->new +() ); # ssh to the server and run "ls" sshopen2( $server, $reader, $writer, 'ls' ) or die "ssh fa +iled $!"; my @rv; while ( <$reader> ) { chomp(); push @rv, $_; } # return the server name and an array ref of filenames return $server, \@rv; }, $_, ); } (@servers); # usual DBI stuff my $dbh = DBI->connect( 'DBI:mysql:database=DATABASENAME;host=localhost;port=3306', 'USERNAME', 'PASSWORD', { 'RaiseError' => 1, 'AutoCommit' => 1 }, ) or die $DBI::errstr; my $sth = $dbh->prepare('INSERT INTO results (server, filename) VALUES + (?,?)'); # wait for threads to complete; insert data into db foreach (@threads) { my ( $server, $files ) = $_->join(); $sth->execute( $server, $_ ) foreach ( @{ $files } ); } $dbh->disconnect();

gryphon
Director Technology, Petfinder.com (Discovery Communications Inc.)
code('Perl') || die;


Comment on Re: Need advice on how to fork with intercommunication
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://630721]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (10)
As of 2015-07-07 18:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls