BigAdmin System Administration Portal
Community-Submitted Tech Tip
Print-friendly VersionPrint-friendly Version
This content is submitted by a BigAdmin user. It has not been reviewed for technical accuracy by Sun Microsystems, though it may have been lightly edited to improve readability. If you find an error or would like to comment on the article, please contact the submitter or use the comment field at the bottom of the article. Community submissions may not follow Sun trademark guidelines. For information on Sun trademarks, please see http://www.sun.com/suntrademarks/.
 
 

How to Safely Interrupt a Sleeping Script

Bátori István, December 2006

Sometimes, instead of using the cron daemon, you write a script that enters a sleep cycle. For example:

while :
do
    doAction
    sleep $sleepTime
done

This method can make it difficult to interrupt the script and restart it while it is sleeping -- particularly if the script has left processes running or if it's important to have only one instance of the script running. You can get around this problem by starting the sleep process in the background, enabling the script to catch the stop signal immediately. Here's an example:

trapAction() {
    echo "exit signal has received, exiting..."

    # you can kill the sleep process here if you like
    [[ -f $TMP_FILE ]] && rm $TMP_FILE
    exit 2
}


trap trapAction INT TERM

while :
do
    doAction
    sleep $sleepTime &
    wait $!
done

Unless otherwise licensed, code in all technical manuals herein (including articles, FAQs, samples) is provided under this License.


BigAdmin