in reply to Self terminating a script after a specified time

If this is *NIX, another way to do it might be to arrange for cron to call killall (or kill if you know the PID; e.g. your script could write it to a file at a known location) at 11:30 the next day, and set up a %SIG handler for that signal in your script for a graceful exit.

  • Comment on Re: Self terminating a script after a specified time

Replies are listed 'Best First'.
Re^2: Self terminating a script after a specified time
by blindluke (Hermit) on Jan 07, 2015 at 19:43 UTC

    If this is *NIX, be very, very careful before you type the word "killall" into your terminal session. Or arrange for cron to call it. On traditional UNIX systems, AIX in particular, it kills all processes except the one calling killall. Kills as in 'SIGKILL', not 'SIGTERM'. Be very, very careful.

    A safer way would be to set up an 'at' job calling 'kill' with the PID of the running process, at the beginning of the script. Or just use Time::Limit. :)

    - Luke

      Using at or cron is not an option. We are mandated to use the corporate approved scheduling system. The goal is to run the process right up until the next 'build' of the daily schedule. Failure to terminate gracefully prior to the next schedule build means I would have a growing number of the same process running which is less than ideal.

        I'm guessing your scheduling system can run Perl scripts: the basic functionality of kill(1) can be implemented in Perl fairly easily with Perl's kill function.

        In regards to the above I later realized you don't even need a second script - using a PID file, your script could kill its previous run when run a second time. Here's a script to demonstrate the idea: Run it once, it will do its "work" for 10 seconds, and if you run it a second time during that time, the second process will kill the first, and do its "work". Since it's just a proof-of-concept this has no handling in the case of being run more than twice, and it's full of potential race conditions (although you did say the invocations will be 24 hours apart).

        use warnings; use strict; # PROOF OF CONCEPT ONLY # - NO race condition protection or file locking # - method for killing not entirely reliable and can loop endlessly # (see e.g. source of Time::Limit for ideas) my $PIDFILE = "foo.pid"; # FIXME: use absolute path $SIG{TERM} = sub { print "exit by signal\n"; exit 0; }; if (-e $PIDFILE) { my $oldpid = do { open my $ifh, '<', $PIDFILE or die $!; <$ifh> }; while ( kill(0,$oldpid) ) { # is proc running & can we signal it? kill 'TERM', $oldpid; sleep 1; } } END { unlink $PIDFILE } open my $ofh, '>', $PIDFILE or die $!; print $ofh $$; close $ofh; sleep 10; # do heavy work print "normal exit\n";