Hi all,
Again, I drown in the muddy watters of child processes:
What I want to achieve is: spawn up to $max_child processes and setup pipes in such
away that all child processes can 'print' to the parent. This because I want to inform
the parent about the exit value of the process
(I know I can set up a signal handler for that, but I have found them very unreliable,
so I want to trry it using pipes)
My output is not what I expected :( Can somebody help me??
This is the code:
#!/bin/env perl
#
use strict;
use FileHandle;
# Global variables;
my $child = 0;
my $max_child = 4;
sub SpawnChild
{
my ($no, $child) = @_;
pipe(READ, WRITE);
autoflush WRITE 1;
# Fork a new child process
my $pid = fork();
if ($pid) {
# This is the parent process
close(WRITE);
return;
}
else { # this is the child
close(READ);
my $sleep = int(rand(6)+1); # a no use random work load
sleep($sleep);
print WRITE "End $no Slept $sleep\n";
exit;
}
}
sub Parent
{
my ($max_iterations) = @_;
for (my $i = 1; $i < $max_iterations; $i++) {
$child++;
print STDOUT "Spawn $i $child\n";
SpawnChild($i, $child);
while ($child >= $max_child) {
my $input = <READ>;
print STDOUT $input;
$child--;
}
}
for (my $i = 1; $i < $max_child; $i++) {
my $input = <READ>;
print STDOUT $input;
$child--;
}
}
This is my output:
Spawn 1 1
Spawn 2 2
Spawn 3 3
Spawn 4 4
End 4 Slept 6
Spawn 5 4
End 5 Slept 2
Spawn 6 4
End 6 Slept 1
Spawn 7 4
End 7 Slept 1
Spawn 8 4
End 8 Slept 2
Spawn 9 4
End 9 Slept 5
So I miss something like
End 1 Slept 6
End 2 Slept 3
End 3 Slept 2
End 4 Slept 4
Where did the 'return print' for the first 4 children go????
Thanks for any suggestions
Jeroen Lodewijks
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]