tags:

views:

775

answers:

1

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?

+2  A: 

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.

dannysauer
This works, even though you might think it doesn't because of what tangens said in the comments on the question. BUT the complete paragraph, qouted partially by tangens, says:
hopla
If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes. When bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed.
hopla
Also want to add that you can kill the whole process group (the process itself and it's children) by doing: kill -TERM -$$
hopla