Ensure a bash process tidies up its children

June 22, 2012 at 2:56 pm Leave a comment

When you have a bash process that spawns a number of background children, there is an unforunate side effect: These processes never exit. If you try to kill their parent they are happilly adopted by init.


Code

Adding the following line at the beginning of your bash script ensure that all your children are truly dead when you yourself are killed.

trap "kill -- -$BASHPID" EXIT

The -PID argument tells bash to kill the process group with id $BASHPID, process groups have the same id as the spawning process (but the process group id remains even after processes have been reparented). The — gets kill not to interpret this as a signal :S.


Caveats

The one caveat here is if someone sends you kill -9. If this happens, you don’t get to do anything before your imminent death (even murder all your children).

Advertisements

Entry filed under: Uncategorized.

Showing the build dependencies of an apt package Samsung Galaxy S2 i9100 over-heating battery symbol fix (Probably water related)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


June 2012
M T W T F S S
« Mar   Aug »
 123
45678910
11121314151617
18192021222324
252627282930  

%d bloggers like this: