TERM 的 bash 陷阱 - 我做错了什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1526746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash trap of TERM - what am I doing wrong?
提问by dannysauer
Given this hack.c program:
鉴于这个 hack.c 程序:
#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:
这个 hack.sh bash 脚本:
#!/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.
如果我运行 hack.sh,则会创建两个进程 - 一个用于 bash,一个用于 C 任务。如果 TERM 信号被发送到 bash 进程,则 C 进程不会受到损害。
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 wantthe C process to die along with the bash that launched it?
现在,假设原始 bash 是使用 Runtime.exec() 从 Java 程序启动的,所以我对它的唯一控制是 Process.destroy()(它将 TERM 发送到 bash 进程)?假设我希望C 进程与启动它的 bash 一起死亡?
I've been trying things like this in bash:
我一直在 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 ignoresTERM signals.
即捕获 TERM 信号并将其重新广播到整个进程组的陷阱子句。这对我不起作用 - 带有该陷阱子句的 bash 进程会忽略TERM 信号。
What am I missing here?
我在这里错过了什么?
回答by dannysauer
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.
陷阱上的双引号应该在定义陷阱时进行单词扩展,因此 $! 不应该有影响;但我更喜欢第一个版本。

