How does this look? The only thing I am worried about is if another
external process happens to inherit the pid of one of the processes I
am about to kill (i.e. it has died already). Is there any way of
making sure the kill -9 is killing a child process and not killing
some other process (this is obviously tiny likelihood but you never
know!)
#!/opt/perl5.8.8/bin/perl
#-------------------------------------------------------------------------------
# Interpreter settings
#-------------------------------------------------------------------------------
use warnings;
use strict;
my $childOnePid;
my $childTwoPid;
my $diePid;
print "Parent process pid=$$\n";
unless (defined ($childOnePid = fork))
{
die "cannot fork: $!";
}
#-------------------------------------------------------------------------------
# Child process loops for 50 seconds
# How to ensure this stops if the parent process dies unexpectedly?
#-------------------------------------------------------------------------------
unless ($childOnePid)
{
print "Inside childOne pid=$$\n";
my @packages = ("Schedule::Cron",
"SOAP::Lite",
"Log::Log4perl",
"MetaMon::MetaMonConfigLoader",
"MetaMon:

haseOne",
"MetaMon::GetEnvVar",
"Data:

umper");
my $package;
eval {
require "PAR.pm";
import PAR q(/opt/perl5.8.8/lib/site_perl/*.par);
for $package (@packages)
{
(my $pkg = $package) =~ s|:

/|g; # require need a path
require "$pkg.pm";
import $package;
}
};
die $@ if( $@ );
for (0..10)
{
sleep 1;
}
print "About to exit childOne\n";
exit;
}
unless (defined ($childTwoPid = fork))
{
die "cannot fork: $!";
}
#-------------------------------------------------------------------------------
# Child process loops for 50 seconds
# How to ensure this stops if the parent process dies unexpectedly?
#-------------------------------------------------------------------------------
unless ($childTwoPid)
{
print "Inside childTwo pid=$$\n";
my @packages = ("Schedule::Cron",
"SOAP::Lite",
"Log::Log4perl",
"Data:

umper");
my $package;
eval {
for $package (@packages)
{
(my $pkg = $package) =~ s|:

/|g; # require need a path
require "$pkg.pm";
import $package;
}
};
die $@ if( $@ );
for (0..12)
{
sleep 1;
}
print "About to exit childTwo\n";
exit;
}
sleep 10;
$diePid = wait();
if ($diePid == $childOnePid)
{
print "Killing child two pid\n";
kill 9, $childTwoPid;
}
elsif ($diePid == $childTwoPid)
{
print "Killing child one pid\n";
kill 9, $childOnePid;
}
elsif ($diePid == -1)
{
#both already dead
sleep 0;
}
else
{
print "Should never get here\n";
}
print "finished\n";
__END__