Hi List
I am trying to write a code which will work as self monitoring script. The
parent will work for something  and child will check that parent program is
running or not . If parent is not running  or somehow killed or crashed then
child will restart the parent . But I am not getting the desired output.
Please rectify my mistake.



use strict;
use warnings;

use File::Basename;
use Cwd qw(realpath);

my $home;
$home = dirname(realpath ($0));
my ($scriptname) = File::Basename::fileparse($0);
my  $scriptname_absolute_path = "$home/$scriptname";
my $pid = $$;
my $count = 0;
my $child_pid = fork;


if ( $child_pid ) {
  print "INSIDE PARENT \n";
#### In the parent #####
#### do some job here #####
} elsif ( $child_pid == 0 ) {
 ## In the Child ####
 do_work();
} elsif  ( not defined $child_pid ) {
   warn "could not fork, waiting two seconds to try again";
   $count += 1;
   if ($count == 5) {
     print "could not fork,resourse busy exititg the program \n";
     exit 0;
   }
   sleep 2;
   next;

}


sub do_work {

 while (1) {
  my $output = `ps -ef | grep $pid | grep -v grep`;
  if ( $output ) {
   sleep 10;
   next;
  } else {
    my $fname = "$scriptname_absolute_path.log";
    print "child $$ working on $fname \n";
    my $datestring;
    if ( ! -s $fname) {
         $datestring = time_check();
         open my $WFH,'>',$fname or die "Can't open $fname $! \n";
         print $WFH "$scriptname_absolute_path terminates at $datestring,
going to start it.\n";
         `perl $scriptname_absolute_path`;
         exit 0;
    } else {
       $datestring = time_check();
       open my $WFH1,'>>',$fname or die "Can't open $fname $! \n";
       print $WFH1 "$scriptname_absolute_path terminates at $datestring,
going to start it.\n";
       `perl $scriptname_absolute_path`;
       exit 0;
    }
  }

 }
}


sub time_check {
 @_ = localtime(time);
 return(sprintf("%02d:%02d %02d/%02d/%04d", @_[2,1], $_[4]+1, $_[3],
$_[5]+1900));
}

Reply via email to