TERM 的 bash 陷阱 - 我做错了什么?
给定这个 hack.c 程序:
#include <stdio.h>
main()
{
int i=0;
for(i=0; i<100; i++) {
printf("%d\n", i);
sleep(5);
}
}
和这个 hack.sh bash 脚本:
#!/bin/bash
./hack
如果我运行 hack.sh,则会创建两个进程 - 一个用于 bash,一个用于 C 任务。如果 TERM 信号被发送到 bash 进程,则 C 进程不会受到损害。
现在,假设原始 bash 是使用 Runtime.exec() 从 Java 程序启动的,所以我对它的唯一控制是 Process.destroy() (它将 TERM 发送到 bash 进程)?假设我希望 C 进程与启动它的 bash 一起终止?
我一直在 bash 中尝试这样的事情:
#!/bin/bash
trap "kill -TERM -$$; exit" TERM
./hack
即捕获 TERM 信号并将其重新广播到整个进程组的 trap 子句。这对我不起作用 - 带有 trap 子句的 bash 进程忽略 TERM 信号。
我在这里缺少什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试按照以下方式进行操作:
这样做可能更简单(且等效):
陷阱上的双引号应该在定义陷阱时使单词扩展发生,因此 $! 的值会发生变化。不应该有影响;但我更喜欢第一个版本。
You might try something along these lines:
It might be simpler (and equivalent) to do this:
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.