I have need of your guidance, for the following problem baffles my impure mind.
The following code works insofar as the Dumper output contains what I expect, but there is no parallel processing -- the children seem to operate sequentially rather than simultaneously.
If I execute the code in the second listing, I can't capture the output, but the children fork and work in parallel.
What am I doing wrong?
Thanks
Listing 2.#!/usr/bin/perl -w use strict; use warnings; use Data::Dumper; use IO::Handle; my @servers = qw/server1 server2 server3/; chomp @servers; my %results = (); my @kids = (); for my $host (@servers) { pipe(CHILD_RDR,PARENT_WTR); PARENT_WTR->autoflush(1); if (my $pid = fork) { close PARENT_WTR; push @kids,$pid; $results{$host} = receive_message(\*CHILD_RDR); close CHILD_RDR; } else { die "Cannot fork: $!\n" unless defined $pid; close CHILD_RDR; my $cmd = q{/usr/bin/ssh } . $host . q{ /bin/date 2>/dev/null} +; my $result = qx{$cmd}; chomp $result; send_message(\*PARENT_WTR,$result); close PARENT_WTR; exit; } } for (@kids) { waitpid($_,0); } print Dumper %results; sub send_message { my $handle = shift; my $msg = shift; print $handle $msg; return; } sub receive_message { my $handle = shift; my $msg; chomp($msg = <$handle>); return $msg; }
#!/usr/bin/perl -w use strict; use warnings; use Data::Dumper; use IO::Handle; my @servers = qw/server1 server2 server3/; chomp @servers; my @kids = (); for my $host (@servers) { if (my $pid = fork) { push @kids,$pid; } else { die "Cannot fork: $!\n" unless defined $pid; my $cmd = q{/usr/bin/ssh } . $host . q{ /bin/date 2>/dev/null} +; my $result = qx{$cmd}; chomp $result; print "$host $result\n"; exit; } } for (@kids) { waitpid($_,0); }
In reply to Forking children operate sequentially?! by darwinscusp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |