|go ahead... be a heretic|
Auto-restarting script if it diesby mojodaddy (Pilgrim)
|on Mar 09, 2007 at 12:24 UTC||Need Help??|
mojodaddy has asked for the
wisdom of the Perl Monks concerning the following question:
Since I am ridiculously new to programming of any kind, scarcely an hour goes by where I am not reminded of the vastness of my ignorance. Still, I've inexplicably fallen in love with perl, so I have no choice but to continue trying to do things I have no idea how to do.
Most recently I set out to find a way to ensure that if a script dies, it is restarted automatically. That way I can go to sleep or maybe even leave the house once in a while. So I dove into perldoc, CPAN, Perl Monks, Google, the Ubuntu forums (I am only marginally less new to Linux than I am to programming), etc., and found loads of stuff relating to PIDs and daemons (I know it's almost baseball season because I keep finding myself typing "damon" instead of "daemon") and forks and parents and children and executing perl scripts from within bash scripts, all of which I found to be either insanely over my head or infuriatingly vague (no offense). I suppose it's like Googling for instructions on how to open the lid of your laptop. It's so obvious that no one thinks to write a tutorial on it.
But when I saw File::Temp on CPAN, a little light went on. All I'd been looking for was simple a way for the script to say "Yes, I'm running," or "No, I'm not running." Why monkey around with a PID or a bash script if I don't need (or know how) to?
So using File::Temp my script (the Script) creates a temporary file when it starts running and which is removed when it stops running:
Then I create and execute a second script (the Checker) which starts the Script, then looks to see if the temp file is there. If it is, it goes to sleep. If not, it restarts the Script:
And it works!
The only peculiar thing about it is that the line "Woo-hoo! Script is still running!" never prints, but when I hit CTRL-C to exit the script, then it prints, and keeps printing every 10 seconds until I hit CTRL-C again. Now that's a bit of a head-scratcher... but did I mention it works?
I welcome your comments and suggestions.
The fix? I don't know why I didn't just set it up this way in the first place, but rather than have the Checker script invoke the Script initially, I simply start the Script myself in the normal way; I remove the first call to start_it() in the Checker, and then start it as a background process. I was delighted to find, another few hours later, that the first instance had died, but that another instance had started up again in a separate terminal window and was whirring merrily away.
Happy, happy days. :)