开发者

bash trap of TERM - what am I doing wrong?

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 r开发者_如何学Cun 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜