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;


In reply to Re: Need advice on how to fork with intercommunication by gryphon
in thread Need advice on how to fork with intercommunication by ewhitt

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.