I'm trying to transfer data to child processes through single pipe. One parent, one pipe, multiple processes.
Now this code has the following problems:
1) The parent immediately writes to the pipe and goes to the expectation of completing child processes.
2) Child processes immediately begin reading from this pipe,
some of them immediately get EOF and die.
therefore, processes get different load
I decided that there is need to use semaphores
Who can tell me how I can implement semaphores here or tell an alternative solution
#!/usr/bin/perl
$file_name='config';
if ( ! open CISCOFILE, $file_name ) {
die "Couldnt open router config file! ($!)";
}
@cisco_list=<CISCOFILE>;
use POSIX qw(:signal_h :errno_h :sys_wait_h);
$SIG{CHLD} = \&REAPER;
sub REAPER {
my $pid;
$pid = waitpid(-1, &WNOHANG);
if ($pid == -1) {
# no child waiting. Ignore it.
} elsif (WIFEXITED($?)) {
$exit_value = $? >> 8;
$signal_num = $? & 127;
$dumped_core = $? & 128;
# print "$pid dead. exit_value=$exit_value, signal_num=$signal_n
+um, dumped_core=$dumped_core\n";
$kids{"$pid"}="$pid dead. exit_value=$exit_value, signal_num=$
+signal_num, dumped_core=$dumped_core\n";
} else {
print "false warn $pid.\n";
}
$SIG{CHLD} = \&REAPER;
}
use IO::Handle;
my ($reader, $writer);
pipe $reader, $writer;
$writer->autoflush(1);
%kids=();
$SIG{INT} = sub { die "$$ dying\n" };
for (1 .. 10) {
unless ($child = fork) {
die "cannot fork: $!" unless defined $child;
squabble( );
exit;
}
$kids{"$child"}="$child start \n";
}
@key_arr=keys(%kids);
foreach $string(@key_arr)
{
print $kids{"$string"};
}
close $reader;
foreach $string(@cisco_list) {
print $writer "$string";
}
close $writer;
#-----Waiting for child processes----
$flag=0;
while($flag==0){
print "\n--------------------\n";
sleep 5;
$flag=1;
@key_arr=keys(%kids);
foreach $string(@key_arr)
{
if($kids{"$string"}=~/start/){$flag=0;}
print $kids{"$string"};
}
}
#------Child process function-------
sub squabble {
close $writer;
open(SUBINTFILE, ">","child $$.txt") or die "Can't open file f
+or writing $!";
select SUBINTFILE;
while ($line = <$reader>) {
chomp($line);
print "$line\n";
sleep 1;
}
close $reader;
}