tags:

views:

2839

answers:

4

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

A: 

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.

Oli
+7  A: 

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.

Johannes Schaub - litb
then how do you killall *child* only ? (or am I missing something obvious)
elmarco
killall kills your children, but not you
orip
elmarco, updated answer
Johannes Schaub - litb
A: 

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.

orip
+2  A: 

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

tokland