Tuesday, March 1, 2011

kill background process when shell script exit

I am looking for a way to clean up the mess when my top-level script exit.

Especially if I want to use "set -e", I wish the background process would die when the script exit.

thanks

From stackoverflow
  • So script the loading of the script. Run a killall (or whatever is available on your OS) command that executes as soon as the script is finished.

  • To clean up some mess, trap can be used. It can provide a list of stuff executed when a specific signal arrives:

    trap "echo hello" SIGINT
    

    but can also be used to execute something if the shell exits:

    trap "killall background" EXIT
    

    It's a builtin, so help trap will give you information (works with bash). If you only want to kill background jobs, you can do

    trap 'kill $(jobs -p)' EXIT
    

    Watch out to use single ', to prevent the shell from substituting the $() immediately.

    elmarco : then how do you killall *child* only ? (or am I missing something obvious)
    orip : killall kills your children, but not you
    Johannes Schaub - litb : elmarco, updated answer
  • Another option is it to have the script set itself as the process group leader, and trap a killpg on your process group on exit.

  • This is usually the simplest and more portable solution:

    trap "kill 0" SIGINT SIGTERM EXIT
    

    kill 0 sends a signal to the process group:

    http://www.opengroup.org/onlinepubs/009695399/functions/kill.html

    Specifying EXIT is very useful if your script has "set -e" and an error happens. See:

    http://www.davidpashley.com/articles/writing-robust-shell-scripts.html

0 comments:

Post a Comment