Question

/bin/sh -version
GNU sh, version 1.14.7(1)

exitfn () {
          # Resore signal handling for SIGINT
    echo "exiting with trap" >> /tmp/logfile
    rm -f /var/run/lockfile.pid    # Growl at user,
    exit                     #   then exit script.
}
trap 'exitfn; exit' SIGINT SIGQUIT SIGTERM SIGKILL SIGHUP

The above is my function in shell script.

I want to call it in some special conditions...like when:

  1. "kill -9" fires on pid of this script
  2. "ctrl + z" press while it is running on -x mode
  3. server reboots while script is executing ..

In short, with any kind of interrupt in script, should do some action eg. rm -f /var/run/lockfile.pid but my above function is not working properly; it works only for terminal close or "ctrl + c"

Kindly don't suggest to upgrade "bash / sh" version.

No correct solution

OTHER TIPS

SIGKILL cannot be trapped by the trap command, or by any process. It is a guarenteed kill signal, that by it's definition cannot be trapped. Thus upgrading you sh/bash will not work anyway.

You can't trap kill -9 that's the whole point of it, to destroy processes violently that don't respond to other signals (there's a workaround for this, see below).

The server reboot should first deliver a signal to your script which should be caught with what you have.

As to the CTRL-Z, that also gives you a signal, SIGSTOP from memory, so you may want to add that. Though that wouldn't normally be a reason to shut down your process since it may be then put into the background and restarted (with bg).


As to what do do for those situations where your process dies without a catchable signal (like the -9 case), the program should check for that on startup.

By that, I mean lockfile.pid should store the actual PID of the process that created it (by using echo $$ >/var/run/myprog_lockfile.pid for example) and, if you try to start your program, it should check for the existence of that process.

If the process doesn't exist, or it exists but isn't the right one (based on name usually), your new process should delete the pidfile and carry on as if it was never there. If the old process both exists and is the right one, your new process should log a message and exit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top