Anirban Adhikary wrote:
Hi List
Hello,
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 .
You want to do that the other way around. The child will do the work and the parent will check that it 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.
Have you read the Interprocess Communication man page? perldoc perlipc
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";
Or: my ( $scriptname, $home ) = File::Basename::fileparse( realpath( $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";
But you don't "try again".
$count += 1; if ($count == 5) {
How do you expect $count to get to 5?
print "could not fork,resourse busy exititg the program \n"; exit 0; } sleep 2; next;
'next' won't work unless you are inside a loop, which you aren't.
} sub do_work { while (1) { my $output = `ps -ef | grep $pid | grep -v grep`;
That is not going to work very well. Suppose $pid contains '78' then that will also match lines where the two digits "78" appear anywhere in the line and not just the PID field.
if ( $output ) { sleep 10; next; } else { my $fname = "$scriptname_absolute_path.log"; print "child $$ working on $fname \n"; my $datestring; if ( ! -s $fname) {
This test is pointless. Just open the file for append and it will work correctly for both cases.
$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)); }
John -- Those people who think they know everything are a great annoyance to those of us who do. -- Isaac Asimov -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/