Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
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 scrutinizing the Monastery: (11)
As of 2014-12-26 14:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (171 votes), past polls