Reputation: 2431
I have a perl script running at any given time and triggering another perl script if a specific condition is met else it sleeps for 1 min. Every time I have to make a modification to the main script and re-run it, I have to ensure no sub-script is running and then kill it and re-run.
So, have been looking if I can reload the perl script automatically based on the modification time. I came across the below link (code snippet shared below) and it works. But wondering, if this is the right way to do it? Any pointers?
Code Snippet here: (test.pl keeps on running and Worker.pm can be modified as needed)
Worker.pm:
package Worker;
our $iteration = 1;
sub do_some_work {
return if $iteration > 100;
printf "$iteration Original\n";
$iteration++;
sleep 1;
return 1;
}
sub save_state {
return $iteration;
}
sub load_state {
my $class = shift;
$iteration = shift;
}
1;
test.pl
#!/usr/bin/env perl
use lib '.';
use Worker;
my $library_file = $INC{'Worker.pm'};
my $library_mtime = ( stat( $library_file ) )[9];
while ( Worker->do_some_work() ) {
my $new_mtime = ( stat( $library_file ) )[9];
next if $new_mtime == $library_mtime;
$library_mtime = $new_mtime;
eval {
my $state = Worker->save_state();
delete $INC{'Worker.pm'};
require 'Worker.pm';
Worker->load_state( $state );
};
}
Source from: https://www.depesz.com/2015/01/21/reloading-of-perl-script-while-its-running/
Upvotes: 1
Views: 837
Reputation: 385887
The simplest solution would be to restart the entire program.
Without external help (doesn't properly exit)
exec($^X, $0);
With external help (exits properly)
exit(254);
plus
#!/bin/sh
while true ; do
program "$@"
e=$?
if [[ $e != 254 ]] ; then
exit $e
fi
done
Upvotes: 1