Warning: preg_replace(): Compilation failed: escape sequence is invalid in character class at offset 4 in /home/customer/www/theunixtips.com/public_html/wp-content/plugins/resume-builder/includes/class.resume-builder-enqueues.php on line 59

bash : Signal Handling

A script could have lock file or is producing temporary files which need to be renamed before exiting. What if the script receives a signal and quits in the middle leaving temporary files scattered around? Bash provides “trap” function to trap a signal and right a signal handler.

if [ ! -e $lockfile ]; then
        # Arm the handler
        trap "rm -f $lockfile; exit" INT TERM EXIT
        touch $lockfile
        critical-section
        rm $lockfile
        # Disarm the handler
        trap - INT TERM EXIT
fi

Or you can write a function like below.

Handle_Exit_Safely()
{
        rm -f $lockfile
        exit
}
if [ ! -e $lockfile ]; then
        # Arm the handler
        trap Handle_Exit_Safely INT TERM EXIT
        touch $lockfile
        critical-section
        rm $lockfile
        # Disarm the handler
        trap - INT TERM EXIT
fi