bash trap of TERM - what am I doing wrong?

user185094 picture user185094 · Oct 6, 2009 · Viewed 9.1k times · Source

Given this hack.c program:

#include <stdio.h>
main()
{
 int i=0;
 for(i=0; i<100; i++) {
   printf("%d\n", i);
   sleep(5);
 }
}

and this hack.sh bash script:

#!/bin/bash
./hack

If I run hack.sh, two processes get created - one for bash, one for the C task. If a TERM signal gets sent to the bash process, the C process is unharmed.

Now, suppose the original bash was launched from a Java program using Runtime.exec(), so the only control I have over it is Process.destroy() (which sends TERM to the bash process)? Suppose I want the C process to die along with the bash that launched it?

I've been trying things like this in bash:

#!/bin/bash
trap "kill -TERM -$$; exit" TERM
./hack

i.e. a trap clause that catches the TERM signal and rebroadcasts it to the whole process group. This doesn't work for me - a bash process with that trap clause in it ignores TERM signals.

What am I missing here?

Answer

dannysauer picture dannysauer · Oct 6, 2009

You might try something along these lines:

#!/bin/bash
./hack &
pid=$!
trap "kill $pid" TERM
wait $pid

It might be simpler (and equivalent) to do this:

#!/bin/bash
./hack &
trap "kill $!" TERM
wait

The double-quotes on the trap should make word expansion happen when the trap is defined, so a changing value of $! shouldn't have an impact; but I like the first version better.